静态数组属性在 php 中是不可能的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11796096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:07:46  来源:igfitidea点击:

Is static array property not possible in php?

phpclassstatic

提问by user1463076

Below is my code in php,and I am getting error:

下面是我在 php 中的代码,我收到错误:

Parse error: syntax error, unexpected '[' in /LR_StaticSettings.php on line 4

解析错误:语法错误,第 4 行 /LR_StaticSettings.php 中出现意外的“[”

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

我想静态使用 not$this->arrErr[$key]以便我可以在不创建实例/对象的情况下获取和设置静态属性。

Why is this error? Can't we create static array?

为什么会出现这个错误?我们不能创建静态数组吗?

If there is another way, please tell me. Thanks

如果有其他方法,请告诉我。谢谢

回答by nickb

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.

你可以在这个演示中看到它的工作。

回答by Matt

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

您的代码未定义$arrErr为静态成员变量。你应该把它声明为

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

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