Reputation: 694
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?
Upvotes: 0
Views: 66
Reputation: 40675
You're asking about hinting but then, in your code, you actually try to do a cast. Which is not necessary and not possible in that way.
Hinting example:
private function __construct(Base $node) {}
Which ensures that you can only pass an instance of Base
or inheriting classes to the function.
Or if it's important for working in your IDE, you can do:
$something = $child->someMethod(); /* @var $child Base */
Which will make sure, your IDE (and other software) know that $child
is of the type Base
.
Instead of casting you could just use is_a
like that:
if (is_a($child, 'Node') {}
else (is_a($child, 'Leaf') {}
But to be honest, it rather seems like you should refactor your code. I don't think it a good idea that a leaf is any different from a node. A leaf is just a node that doesn't have any children, which you can test anytime with $node->hasChildren()
and even set and unset a leaf flag, if you need to.
Upvotes: 1
Reputation: 4916
This is not proper OOP. Try this instead:
Add method sum
to Base
(abstract if you don't want to implement). Implement this same method sum
for Leaf
, which would simply return it's getValue
. Then you can simply call sum
on both types, thus no need for case, or to know it's type and so on:
foreach ($children as $child) {
$sum += $child->sum();
}
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:
/* @var $varName Type_Name */
Upvotes: 1