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

自作多情 提交于 2019-12-11 07:55:37

问题


While I was creating a class in php, I experienced this error:

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

A simple example:

<?php

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

?>

I already had a look at Reference - What does this error mean in PHP? but this doesn't seem to fit to my case. The problem of all other existing Questions seem to rely to an old PHP Version. But I am using PHP 5.6.3!

What can I do? Am I just sightless?


回答1:


You can't explicitly create a variable like that (array index). You'd have to do it like this:

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

Alternatively, you could do (as most people would), this:

class MyClass {
    public $variable = array();

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



回答2:


I guess you should declare it the way it is shown below :

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



回答3:


Make an array first. Use the code below

<?php

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

}

?>

HOpe this helps you




回答4:


You cannot declare class members like this. Also you cannot use expressions in class member declarations.

There are two ways to achieve what you are looking for :

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

or like this

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


来源:https://stackoverflow.com/questions/27887187/php-5-6-3-parse-error-syntax-error-unexpected-in-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!