I’m am a newb with the whole class inheritance in general but I am a bit more confused with php.
I would like to have the following:
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;
}
}
For public sum(), I want something like:
$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;
Not sure how to do the cast. Also would the array store the type of the added $item?
This is not proper OOP. Try this instead:
Add method
sumtoBase(abstract if you don’t want to implement). Implement this same methodsumforLeaf, which would simply return it’sgetValue. Then you can simply callsumon both types, thus no need for case, or to know it’s type and so on:This is called polymorphism and it’s one of the basic concepts of object oriented programming.
To also answer your question, you can hint type locally in Netbeans and Zend Studio (and probably other editors) with: