类属性声明 [英] class attribute declaration

查看:124
本文介绍了类属性声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用PHP,但我尝试过这样的:

I didn't use PHP in a while, but I've tried something like this:

<?php

class Something {
    public $x = 2 * 3;   // (line 4)
}

此代码会触发以下错误:

This code triggers the following error:


[2013年2月13日17:43:56] [错误] [客户端127.0.0.1] PHP解析错误:语法错误,意外的'*' ,在第4行的/var/www/problem.php中预期为','或';'。

[Wed Feb 13 17:43:56 2013] [error] [client 127.0.0.1] PHP Parse error: syntax error, unexpected '*', expecting ',' or ';' in /var/www/problem.php on line 4

PHP文档


这个初始化必须是一个常量值 - 也就是说,它必须能够在编译时进行求值,并且不能依赖运行时信息来进行求值。

this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

所以,根据文档,我的代码应该工作。

So, according to the docs, my code should work. Is there something I'm missing here?

推荐答案

当声明一个类的成员时,你可以给它们赋值,但你可以' t做复杂的操作,如数学或函数调用。

When declaring members of a class you can assign values to them but you can't do complex operations like math or function calls.

<?php

class Something {
    public $x = 2 * 3;   // (line 4)
}

可以是:

<?php

class Something {
    public $x = 6;   // (line 4)
}

所以在你的case你会想初始化

So in your case you'll want to initialize that value in your constructor instead.

<?php

class Something {
    public $x; 

    public function __construct() 
    {
        $this->x = 2 * 3;
    }  
}

这篇关于类属性声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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