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
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
Static properties ¶ Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ).
Definition and UsageThe static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.
Actually, static variables in PHP are not static at all.. their values can be changed during execution.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With