tekmosis blogged

Late Static Binding of variables and constants in PHP 5.3

In PHP 5.3 you can do Late Static Binding

Through some testing I found that you can overwrite the value of the parents values for both variables and constants by using them statically in the parent class. Here's an example.

__phpcode0__

Our class is very generic, we have a static class variable $foo and a constant bar. We also have two supporting functions that will echo out each value. Note that we are using static:: on both and not $this-> or self::

__phpcode1__

This is our child class where we again define $foo and bar but we set the values differently. Again we have two functions but they're calling the parent functions to echo both values.

The script is set up and executed as such,
__phpcode2__

The result
quote
child var
child const
as you can see we have successfully modified the variables used in the parent class through the child via Late Static Binding.

technology

Responses (3)

0 thumbs!
#
bobbonew Apr 18, 11
nom nom nom nom *NOM!
0 thumbs!
#
Chiggins Apr 18, 11
Nice posting. Curious though, where would something like this be useful? Dunno if I just can't think of anything, or if I'm too tired to really think.
0 thumbs!
#
tekmosis Apr 18, 11
Say class A was for an 87' Impala. Now, you want to release a 2012 Impala (class B). On the 87 you had $include_tape_deck = true; well, not like you need that on the 2012 model so in the 2012 Impala you set $include_tape_deck = false;

Any function in the 87' Impala that use static::$include_tape_deck will now be false even though the original is still set to true.
(0.0381/d/www1)