PHP在Iterator中调用方法

时间:2016-04-08 09:23:29

标签: php methods iterator

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

提前致谢 A.pe

class MapComparator<K,V extends Comparable<V>> implements Comparator<Map<K,V>> {

  public int compare(Map<K,V> m1, Map<K,V> m2) {
     return m1.get(sortby).compareTo(m2.get(sortby));
  }

}

1 个答案:

答案 0 :(得分:0)

就这样打电话:

$a->getNumber();

此处$amyArrayObj类的对象。您可以根据其property从课程外部拨打任何methodaccess modifier

完整代码:

<?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);
    }
}