2010-12-07 52 views
3

这里是一个最小的测试用例我隔离:PHP类属性使用范围()

<?php 

class What { 
    public $foo = range(0,5); 
} 

?> 

我不知道为什么这会产生一个错误:

PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in TestCase.php on line 4

使用array()作品。

使用PHP 5.3.3(与OS X捆绑)。

+3

你的评论,“许多其他功能的工作”不能是正确的。 – Matthew 2010-12-07 06:10:07

+0

@konforce故事的寓意在于,不要在深夜问到超级堆栈溢出问题。 D: – Karew 2010-12-08 23:43:03

回答

5

您只能在该上下文中分配常量值。如果要使用函数的返回值,则必须在构造函数中初始化$foo

<?php 

class What { 
    public $foo; 

    public function __construct() { 
     $this->foo = range(0,5); 
    } 
} 

?> 

顺便说一句:正如其他人指出的,array()不是一个函数。这是一种语言结构。

1

数组不是函数,它是一种语言结构。这就是允许它的原因。

0

Class member variables are called "properties" ... 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.

http://www.php.net/manual/en/language.oop5.properties.php

0

检查此链接为一个类似的问题被发送,已经得到了解决: - 在PHP

http://www.phpbuilder.com/board/showthread.php?t=10366062

还可以看到使用范围的例子()函数.Net手册,尽管我认为问题可能出现在变量$ foo和public关键字中,因为您可能会遇到类型不匹配或PHP函数版本与正在运行的PHP版本冲突的情况。

我希望这个答案可以帮助你..