note 33092 deleted from language.oop by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 19:04:04 +0000 |
| Subject: | note 33092 deleted from language.oop by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162571@lists.php.net to get a copy of this message | ||
Note Submitter: oran at anonimous dot biu dot ac dot il
----
class baseclass {
function static1() {return "bla";}
function static2() {return call_user_func(array(__CLASS__,'static1'));}
}
[ Editor's Note: Using the above, rather than below, will allow the static function to call its
own generation's version of the method. ]
Unfortunately, inheritance of static methods is a bit problematic in PHP, because in order to use a
static method you have to know the exact class it's defined in. This means trouble if you want
to use one static function (or a static variable) from within another static function. For example:
class baseclass {
function static1() {return "bla";}
function static2() {return baseclass::static1();}
}
Now suppose that you write a class newclass that extends baseclass and redefines static1() to return
"foo" instead of "bla" - this change will not be reflected in static2() of
newclass. Not good at all.
You could use $this->static1() instead of baseclass::static1() in the definition of static2(),
but then static2() will not be a static method. Another idea is to use get_class_name() to get the
class name inside static2(), but again you need the $this variable to make this function call.
I found no way to overcome this problem, except to use real functions (not methods) for the purpose
of wrapping my static functions. The name of the exact class to use is passed as a parameter to the
wrapping function. It looks like this:
function wrapped_static1($clname) {
if (in_array('static1', get_class_methods($clname)))
return $clname::static1();
return baseclass::static1();
}
function wrapped_static2($clname) {
if (in_array('static2', get_class_methods($clname)))
return $clname::static2();
return baseclass::static2();
}
class baseclass {
function static1() {return "bla";}
function static2() {return wrapped_static1('baseclass');}
}
Now you can go on using baseclass and writing extension classes for it, using the following rules:
1. Use inheritance with your static functions in the natural way, as you would in C++. The wrapping
code given here supports just 1 level of inheritance, but it may be improved to work its way up the
inheritance tree using PHP's class functions.
2. When calling a static function, always call it through its wrapper.
For example:
class newclass extends baseclass // example for rule 1
{
function static1() {return 'foo';}
}
print static2_wrapper('newclass'); // example for rule 2
This is a little cumbersome, but now when you redefine a static function, you can be sure that any
functions that rely on it will be able to use the correct definition.