note 49018 added to language.oop5.static

From: Date: Fri, 14 Jan 2005 15:11:23 +0000
Subject: note 49018 added to language.oop5.static
Groups: php.notes 
Request: Send a blank email to php-notes+get-83254@lists.php.net to get a copy of this message
Both static and const fields can be accessed with the :: operator. However, while a constant can't be changed, this is not true for static variables. If you want to access an array using the :: operator you have to declare the array static, since you can't have a constant array. Beware: <?php class foo { static $stuff = array('key1' => 1, 'key2' => 2); } class bar { public function __construct() { var_dump(foo::$stuff); } } class bad { public function __construct() { foo::$stuff = FALSE; } } new bar(); // prints array(2) { ["key1"]=> int(1) ["key2"]=> int(2) } new bad(); new bar(); // prints bool(false) ?> A safe implementation requires a little more effort: <?php class foo { private static $stuff = array('key1' => 1, 'key2' => 2); public final static function getstuff() { return self::$stuff; } } class bar { public function __construct() { var_dump(foo::getstuff()); } } class bad { public function __construct() { foo::$stuff = FALSE; } } new bar(); // prints array(2) { ["key1"]=> int(1) ["key2"]=> int(2) } new bad(); // results in a fatal error ?> ---- Manual Page -- http://www.php.net/manual/en/language.oop5.static.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+49018 Delete -- http://master.php.net/manage/user-notes.php?action=delete+49018&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49018&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+49018&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+49018&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+49018&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+49018&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+49018&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#83254) next »