note 48233 added to language.oop5.static

From: Date: Thu, 16 Dec 2004 07:09:05 +0000
Subject: note 48233 added to language.oop5.static
Groups: php.notes 
Request: Send a blank email to php-notes+get-81845@lists.php.net to get a copy of this message
If you are trying to write classes that do this: <?php class Base { static function Foo () { self::Bar(); } } class Derived extends Base { function Bar () { echo "Derived::Bar()"; } } Derived::Foo(); // we want this to print "Derived::Bar()" ?> Then you'll find that PHP can't (unless somebody knows the Right Way?) since 'self::' refers to the class which owns the /code/, not the actual class which is called at runtime. (__CLASS__ doesn't work either, because: A. it cannot appear before ::, and B. it behaves like 'self') But if you must, then here's a (only slightly nasty) workaround: <?php class Base { function Foo ( $class = __CLASS__ ) { call_user_func(array($class,'Bar')); } } class Derived extends Base { function Foo ( $class = __CLASS__ ) { parent::Foo($class); } function Bar () { echo "Derived::Bar()"; } } Derived::Foo(); // This time it works. ?> Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.) If Foo() takes parameters then list them before $class=__CLASS__ and in most cases, you can just forget about that parameter throughout your code. The major caveat is, of course, that you must override Foo() in every subclass and must always include the $class parameter when calling parent::Foo(). ---- Manual Page -- http://www.php.net/manual/en/language.oop5.static.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+48233 Delete -- http://master.php.net/manage/user-notes.php?action=delete+48233&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48233&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48233&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48233&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48233&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48233&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+48233&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#81845) next »