PHP类中变量的初始化只能是定值 (PHP心得)
发布于 2010-04-14 18:19 阅读:160,859 评论:0 标签: Opcodes 初始化

    首先看代码:

以下是引用片段:
class test
{
        //private $_expire_time =  604800; // 604800 = 60 * 60 * 24 * 7
        private $_expire_time =  60 * 60 * 24 * 7;
        public function hehe()
        {
                echo $this->_expire_time;
        }
}
$a = new test;
$a->hehe();
?>
[root@sso115 append]# php test.php
PHP Parse error:  syntax error, unexpected ’*’, expecting ’,’ or ’;’ in /data1/f2r/append/test.php on line 5
Parse error: syntax error, unexpected ’*’, expecting ’,’ or ’;’ in /data1/f2r/append/test.php on line 5

    杯具了,这句话有语法错误:

以下是代码片段:
private $_expire_time =  60 * 60 * 24 * 7;

    那么,这是为什么呢?

    查看手中的手册,没发现有解释,查看官方文档:http://www.php.net/manual/en/language.oop5.properties.php,如下:

以下是引用片段:
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but 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.

    如红色字体,翻译如下:

以下是引用片段:
    这个声明可能会包含初始化,当时这个初始化必须是一个定值,也就是说,这个定值必须在编译时就能确定,而不是依赖于php在运行时再确定值。

    呃,翻译的有点拗口。简而言之,就是说类里面变量的初始化不能是一个表达式,否则编译期间就编译不过去,产生不了Opcodes。

    手册中给出错误和正确的初始化的例子:

以下是代码片段:
class SimpleClass
{
   // invalid property declarations:
   public $var1 = ’hello ’ . ’world’;
   public $var2 = <<hello world
EOD;
   public $var3 = 1+2;
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = array(true, false);

   // This is allowed only in PHP 5.3.0 and later.
   public $var8 = <<<’EOD’
hello world
EOD;
}
?>

    关于Opcodes和编译的过程,可以参考以下资料:

以下是引用片段:
深入理解PHP原理之Opcodes
http://www.laruence.com/2008/06/18/221.html

PHP编译缓存
http://www.allniu.com/2010/0108/3820.html

实现PHP的编译执行分离(separating compilation and execution)
http://www.phpchina.com/index.php?action-viewnews-itemid-34001

    说句题外话:

    据说,现在PHP官网没有提供中文文档入口,是因为中文文档没人维护的原因,杯具!:http://opensource.solidot.org/article.pl?sid=08/04/22/2359251

    不过随便进入文档任意语言页面,切换语言中选 "Other",还是可以进入中文文档的。

展开全文  
收起全文