【问题标题】:PHP invoke method inside Iterator迭代器内的 PHP 调用方法
【发布时间】:2016-04-08 09:23:28
【问题描述】:

我是面向对象的初学者,我想知道是否可以使用一些强制转换、魔术方法或面向对象工程来调用下面注释代码中的内容?

提前致谢 佩佩

<?php
Class myArrayObj  {
    public $myArray ;

    function __construct(){
        $this->myArray = array( 
    0 => 'a', 
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))), 
    2 => 'b', 
    3 => array('subA','subB','subC'), 
    4 => 'c'
    );
    }

    function getNumber() {
        return count($this->myArray);   
    }
}

$a = new myArrayObj();

$i = new RecursiveIteratorIterator(new RecursiveArrayIterator($a),RecursiveIteratorIterator::SELF_FIRST);

foreach($i as $key => $value) {
$type = gettype($value);
$depth = $i->getDepth();

if($i->hasChildren()) {
        echo "$depth: $key ($type) has children<br>";
        /* here is it possible to call ....->getNumber(); */
    } 
    else {
        echo "$depth: $key ($type) has no children<br>";
        /* here is it possible to call ....->getNumber(); */
    }
}

【问题讨论】:

  • 你可以简单地做$a-&gt;getNumber(),但我觉得我在这里没有正确理解这个问题。
  • “是否可以使用某种强制转换、魔术方法或面向对象的工程来调用下面注释代码中的内容?” - 不。因为与原始对象的关系被破坏了。 RecursiveArrayIterator 会将对象转换为数组。

标签: php methods iterator


【解决方案1】:

这样调用:

$a->getNumber();

这里$amyArrayObj 类的对象。您可以根据 access modifier 从类外部调用任何 propertymethod

完整代码:

<?php
Class myArrayObj  {
    public $myArray ;

    function __construct(){
        $this->myArray = array( 
    0 => 'a', 
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))), 
    2 => 'b', 
    3 => array('subA','subB','subC'), 
    4 => 'c'
    );
    }

    function getNumber() {
        return count($this->myArray);
    }

    function countArray($ar) {
        return count($ar);
    }
}

$a = new myArrayObj();

$i = new RecursiveIteratorIterator(new RecursiveArrayIterator($a),RecursiveIteratorIterator::SELF_FIRST);

foreach($i as $key => $value) {
$type = gettype($value);
$depth = $i->getDepth();

if($i->hasChildren()) {
        echo "$depth: $key ($type) has children<br>";
        /* here is it possible to call ....->getNumber(); */
        echo $a->countArray($value);
    } 
    else {
        echo "$depth: $key ($type) has no children<br>";
        /* here is it possible to call ....->getNumber(); */
        echo $a->countArray($value);
    }
}

【讨论】:

  • 嗨,我的意图是通过 $i RecursiveIterator 调用 ->getName()。
  • 对于主数组中的每个数组派生器获取计数元素...并不总是主数组的计数...现在更清楚了吗?
  • 是的,你可以。只需在需要的地方调用该方法即可。
  • 你能实现或想要我吗?先自己试试吧。
  • 我昨天花了一些时间,我尝试 $i->getName() 但当然这是不可能的,因为 RecursiveIteratorIterator 和 myArrayObj 之间没有任何关系,我尝试使用扩展 myArrayObj RecursiveIteratorIterator 但没有结果......我必须做一些演员?
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 2017-03-12
相关资源
最近更新 更多