我是一个拥有整个类继承的新手,但我对 php 有点困惑。
我想要以下内容:
class Base
{
//some fields and shared methods...
}
class Node
{
private $children = array();
public function getChildren()
{
...
}
public function addChild($item)
{
$children[] = $item;
}
public function sum()
{
}
}
I want $item to be either another Node or a Leaf:
class Leaf extends Base
{
private $value;
public getValue()
{
}
public setValue($someFloatNumber)
{
$this->value = $someFloatNumber;
}
}
对于公共总和(),我想要类似的东西:
$sum = 0;
foreach ($children as $child)
{
switch(gettype($child))
{
case "Node":
$sum+= ((Node) $child)->sum();
break;
case "Leaf":
$sum+= ((Leaf) $child)->getValue();
break;
}
}
return $sum;
不知道怎么做演员表。数组还会存储添加的 $item 的类型吗?