PHP 5.6.3解析错误:语法错误,在类中出现意外的'[''

当我在php中创建一个类时,我遇到了这个错误:

Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 5 

一个简单的例子:

<?php

class MyClass
{
  public $variable["attribute"] = "I'm a class property!";
}

?>

我已经看过参考文献 - 这个错误在PHP中意味着什么? 但这似乎不适合我的情况。 所有其他现有问题似乎都依赖于旧的PHP版本。 但我使用PHP 5.6.3!

我能做什么? 我只是没有视力吗?


你不能显式地创建一个像这样的变量(数组索引)。 你必须这样做:

class MyClass {
    // you can use the short array syntax since you state you're using php version 5.6.3
    public $variable = [
        'attribute' => 'property'
    ];
}

或者,你可以这样做(就像大多数人那样):

class MyClass {
    public $variable = array();

    function __construct(){
        $this->variable['attribute'] = 'property';
    }
}
// instantiate class
$class = new MyClass();

我想你应该按照下面的方式声明它:

class MyClass
{
   public $variable = array( "attribute" => "I'm a class property!" );
}

先创建一个数组。 使用下面的代码

<?php

class MyClass
{
public $variable = array("attribute"=>"I'm a class property!");

}

?>

HOpe这可以帮助你

链接地址: http://www.djcxy.com/p/11957.html

上一篇: PHP 5.6.3 Parse error: syntax error, unexpected '[' in class

下一篇: PHP Array Syntax Parse Error Left Square Bracket "["