note 49018 deleted from language.oop5.static by cmb
| From: | cmb@php.net | Date: | Sun, 01 Sep 2019 07:29:15 +0000 |
| Subject: | note 49018 deleted from language.oop5.static by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212055@lists.php.net to get a copy of this message | ||
Note Submitter: ference at super_delete_brose dot co dot uk
----
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
?>