简体   繁体   English

的PHP-语法错误,意外的'(',期待')'

[英]php - syntax error, unexpected '(', expecting ')'

I was developing a site using Laravel 4. I had this piece of code in one of my models: 我正在使用Laravel 4开发一个站点。在我的一个模型中有以下代码:

class MyModel extends Eloquent {
    protected $var = array(
        "label" => Lang::get("messages.label"),
        "code" => "myCode",
    );
    ...
}

But I gave this syntax error on the line where I used Lang::get : 但是我在使用Lang::get的那一行上给出了这个语法错误:

syntax error, unexpected '(', expecting ')'

Then I changed my code into this: 然后我将代码更改为:

class MyModel extends Eloquent {
    protected $var;

    public function __construct() {
        $this->var = array(
            "label" => Lang::get("messages.label"),
            "code" => "myCode",
        );
    }
}

And the error went gone! 错误消失了! I think the error is very confusing and unhelpful. 我认为该错误非常混乱且无济于事。 Why does php show this error message? 为什么php显示此错误消息?

It is because you use Lang::get() when defining a class property, which is not allowed. 这是因为在定义类属性时使用了Lang::get() ,这是不允许的。 Calling stuff like static methods can only be done at runtime (when the code is being executed). 只能在运行时 (执行代码时)执行诸如静态方法之类的调用。

When you define classes their properties can only be non-variable (or "constant") values (such as integers, strings or arrays that themselves only contain non-variable values). 当定义类时,它们的属性只能是非变量(或“常数”)值(例如本身仅包含非变量值的整数,字符串或数组)。

Runtime code should be put into the constructor. 运行时代码应放入构造函数中。

The issue is because you're calling Lang::get which is a function when initializing your class attribute, and default values for class attributes can only be constant values. 问题是因为您在初始化类属性时调用的是Lang :: get函数,而类属性的默认值只能是常量值。

You're correct to initialise these attributes in the constructor instead. 您正确地在构造函数中初始化这些属性是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 解析错误:语法错误,意外的 '[',期待 ')' php - Parse error: syntax error, unexpected '[', expecting ')' php PHP解析错误:语法错误,意外的“:”,期待“;” 或者 '{' - PHP Parse error: syntax error, unexpected ':', expecting ';' or '{' 语法错误,意外'。',在config.php中期待']' - syntax error, unexpected '.', expecting ']' in config.php 语法错误,意外的'[',期望')' - Syntax error, unexpected '[', expecting ')' 语法错误,意外'。',期待')' - syntax error, unexpected '.', expecting ')' 解析错误:语法错误,意外的'[',期望')',可能是PHP版本问题 - Parse error: syntax error, unexpected '[', expecting ')', possibly PHP version issue Wordpress插件PHP解析错误:语法错误,意外的“ {”,预期为“)” - Wordpress plugin PHP Parse error: syntax error, unexpected '{', expecting ')' 解析错误:语法错误,意外的';',期望的是')'(Wordpress functions.php) - Parse error: syntax error, unexpected ';', expecting ')' (Wordpress functions.php) PHP 版本 4:: 解析错误:语法错误,意外 '=',期待 ')' - PHP version 4 :: Parse error: syntax error, unexpected '=', expecting ')' PHP解析错误:语法错误,意外的T_IS_EQUAL,预期 - PHP Parse error: syntax error, unexpected T_IS_EQUAL, expecting
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM