I have a base class that I need to call functions on a class that is referenced in the child class.
Easy enough,
class base_class {
public function doSomethingWithReference(){
$this->reference->doSomething();
}
}
class extended_class extends base_class{
protected $reference;
public function __construct($ref){
$this->reference = $ref;
}
}
Now this works fine obviously,
But, when I am debugging I don’t care about the value of $this->reference
But, the object that $this->reference refers to is huge!
so, when I do print_r($instanceOfExtendedClass) I get the print out of that object.
Now the reference is different for each class that extends base_class.
What I wanted to do was just set reference as a static property on the extended_class class.
But, then changing doSomethingWithReference to be self::$reference throws an undefined variable error.
And conversely setting the static variable in base_class and modifying it from extended_class doesn’t work as it changes the variable for all everything that extends from that class.
Is there any way to do this so I don’t get the print out of $this->reference?
Because you are using PHP 5.3, you can use late static binding to resolve the static call to the right class at runtime.
Big fat reminder: That one
extended_class::$referenceis going to be shared amongst all of theextended_classinstances. If that is not what you intend, this is not going to work.You seem to actually be worried about memory or resource use. In PHP, all objects are passed by reference. This means that passing an object as an argument, or creating a copy of it, etc, does not consume extra memory. If you need to reference an object in a number of other objects, doing so will not consume extra memory.
It looks like the sharing is based on where the static variable is defined. Two examples, both from the PHP interactive prompt:
In this case, because the reference lives in the base class, everyone sees the same one. I suppose this makes some sort of sense.
What happens when we declare the reference with each child class.. most of the time?
Because 3 inherited from 1 without declaring it’s own static property, it inherited 1’s. When we set 3’s to Shared(3), it overwrote 1’s existing Shared(1).
Conclusion: For this to work, the property needs to be declared in every class that needs the single unique reference. Note that this code is valid as of 5.4.x.