Is static array property not possible in php?
22,389
You'd need to declare the variable as a static member variable, and prefix its name with a dollar sign when you reference it:
class StaticSettings{
private static $arrErr = array();
function setkey($key,$value){
self::$arrErr[$key] = $value;
}
}
You'd instantiate it like this:
$o = new StaticSettings;
$o->setKey( "foo", "bar");
print_r( StaticSettings::$arrErr); // Changed private to public to get this to work
You can see it working in this demo.
Author by
user1463076
Updated on October 24, 2020Comments
-
user1463076 over 3 years
Below is my code in php,and I am getting error:
Parse error: syntax error, unexpected '[' in /LR_StaticSettings.php on line 4
<?php class StaticSettings{ function setkey ($key, $value) { self::arrErr[$key] = $value; // error in this line } } ?>
I want to use statically not
$this->arrErr[$key]
so that I can get and set static properties without creating instance/object.Why is this error? Can't we create static array?
If there is another way, please tell me. Thanks
-
user1463076 almost 12 yearsHey thanks. I missed $ sign. now it's working.
class StaticSettings{ private static $arrErr = array(); function setkey($key,$value){ self::$arrErr[$key] = $value; } }
. it was my silly mistake. -
user1463076 almost 12 yearsIn php there is no need to define variable. we simple use it. No need to write,
private static $arrErr = array();
-
nickb almost 12 years@user1463076 - That is not true. When you omit it, a fatal error is produced.