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

From: Date: Fri, 29 Jul 2022 07:14:48 +0000
Subject: note 127363 added to language.oop5.late-static-bindings
Groups: php.notes 
Request: Send a blank email to php-notes+get-219077@lists.php.net to get a copy of this message
You must be careful when getting static property of extended class from parent class, in example below you can see that using property_exists (method getA2) instead of isset with static keyword (method getA1) to check if the static property exist gives much more intuitive result: <?php class Foo { public static string $A; public static function init() { return static::class; } public static function getA1() { if (!isset(static::$A)) { static::$A = static::class; } return static::$A; } public static function getA2() { if (property_exists(static::class, 'A')) { static::$A = static::class; } return static::$A; } } class Bar extends Foo {} $foo = new Foo(); echo $foo->getA1(); echo $foo->getA2(); echo $foo->getA1(); $bar = new Bar(); echo $bar->getA1(); echo $bar->getA2(); echo $bar->getA1(); ?> Output: Foo Foo Foo Foo Bar Bar Notice how $bar->getA1() returns "Foo" instead of "Bar" that many people would expect to see. ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 213.147.120.136) ---- Manual Page -- https://php.net/manual/en/language.oop5.late-static-bindings.php Edit -- https://main.php.net/note/edit/127363 Del: integrated -- https://main.php.net/note/delete/127363/integrated Del: useless -- https://main.php.net/note/delete/127363/useless Del: bad code -- https://main.php.net/note/delete/127363/bad+code Del: spam -- https://main.php.net/note/delete/127363/spam Del: non-english -- https://main.php.net/note/delete/127363/non-english Del: in docs -- https://main.php.net/note/delete/127363/in+docs Del: other reasons-- https://main.php.net/note/delete/127363 Reject -- https://main.php.net/note/reject/127363 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219077) next »