11

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

2
  • Your code doesn't define $arrErr as a static member variable. You should declare it as public static $arrErr = array(); Commented Aug 3, 2012 at 12:52
  • No reason for vote down? I find this question help me. So, vote up. BTW, OP should consider to accept the answer Commented Mar 19, 2015 at 10:50

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey 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.
In php there is no need to define variable. we simple use it. No need to write, private static $arrErr = array();
@user1463076 - That is not true. When you omit it, a fatal error is produced.
0

Your code doesn't define $arrErr as a static member variable. You should declare it as

<?php
class StaticSettings{
    public static $arrErr = array();

    function setkey($key,$value){
        self::arrErr[$key] = $value;
    }
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.