PHP类中变量的初始化只能是定值

芽雨快跑 2010-04-19 09:45:59 累计浏览 3,114 次
    首先看代码:
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",还是可以进入中文文档的。

同分类推荐文章

  1. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,702)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,568)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,821)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,719)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 13,274)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,949)
  7. Redis消息队列的若干实现方式 (累计阅读 12,536)
  8. 到底什么是MVC? (累计阅读 12,385)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 12,222)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,972)