note 112004 added to language.oop5.late-static-bindings

From: Date: Sun, 21 Apr 2013 07:20:04 +0000
Subject: note 112004 added to language.oop5.late-static-bindings
Groups: php.notes 
Request: Send a blank email to php-notes+get-194580@lists.php.net to get a copy of this message
On about the fourth try, I finally found a usable LSB emultation for php < 5.3, with minimum extra typing. <?php // HELPER CLASS - use as-is class StaticWrapper { function __construct($className) { $this->class = $className; } function __get($name) { $class = new ReflectionClass($this->class); try { return $class->getStaticPropertyValue($name); } catch (ReflectionException $e) { return $class->getConstant($name); } } function __call($name, $args) { return call_user_func_array(array($this->class, $name), array_merge(array($this), $args)); } } // USAGE EXAMPLE class A { const C = "CA"; public static function S() { return new StaticWrapper(__CLASS__); } // must be in every inherited class static function f($S) { $S->g(); echo "C = " . $S->C . "\n"; } static function g($S) { echo "A\n"; } function nonstatic() { $this->S()->f(); } } class B extends A { const C = "CB"; public static function S() { return new StaticWrapper(__CLASS__); } // must be in every inherited class static function g($S) { echo "B\n"; parent::g($S); } } B::S()->f(); $b = new B; $b->nonstatic(); // Both print: // B // A // C = CB ?> The semantics are exactly the same as in PHP 5.3 for static functions and constants, only a little extra typing. It also supports static member variables, however, that is useless because of another bug/misfeature of PHP < 5.3: <?php class A { public static $v = 5; } class B { public static $v = 42; } echo A::$v; //prints 42 ?> I.e., (emulated) LSB has no use here as PHP forces the variable in the parent and child class to have the same value, therefore you can just as well use self::. ---- Server IP: 69.147.83.199 Probable Submitter: 77.48.29.130 ---- Manual Page -- http://php.net/manual/en/language.oop5.late-static-bindings.php Edit -- https://master.php.net/note/edit/112004 Del: integrated -- https://master.php.net/note/delete/112004/integrated Del: useless -- https://master.php.net/note/delete/112004/useless Del: bad code -- https://master.php.net/note/delete/112004/bad+code Del: spam -- https://master.php.net/note/delete/112004/spam Del: non-english -- https://master.php.net/note/delete/112004/non-english Del: in docs -- https://master.php.net/note/delete/112004/in+docs Del: other reasons-- https://master.php.net/note/delete/112004 Reject -- https://master.php.net/note/reject/112004 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194580) next »