PHP 5.6.3解析错误:语法错误,意想不到的'['类 [英] PHP 5.6.3 Parse error: syntax error, unexpected '[' in class

查看:126
本文介绍了PHP 5.6.3解析错误:语法错误,意想不到的'['类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我是PHP创建类,我经历了这个错误:

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

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

一个简单的例子:

<?php

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

?>

我已经有了一看<一个href=\"http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/22316776#22316776\">Reference - 这是什么错误在PHP中的意思是但这似乎并不适合我的情况?所有其他现有问题的问题似乎依赖于一个古老的PHP版本。但我使用PHP 5.6.3!

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?

推荐答案

您不能明确创建类似的(数组索引)的变量。你必须做这样的:

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();

这篇关于PHP 5.6.3解析错误:语法错误,意想不到的'['类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆