Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is static array property not possible in php?

Tags:

php

class

static

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 image 478
user1463076 Avatar asked Aug 03 '12 12:08

user1463076


People also ask

What is static array in PHP?

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.

What is static property PHP?

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 ).

What are static methods in PHP?

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.

Can we change static variable value in PHP?

Actually, static variables in PHP are not static at all.. their values can be changed during execution.


1 Answers

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.

like image 193
nickb Avatar answered Oct 17 '22 05:10

nickb