【发布时间】: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->getNumber(),但我觉得我在这里没有正确理解这个问题。 -
“是否可以使用某种强制转换、魔术方法或面向对象的工程来调用下面注释代码中的内容?” - 不。因为与原始对象的关系被破坏了。
RecursiveArrayIterator会将对象转换为数组。