2009-10-27 53 views
12

当您在php中声明属性时,为什么不能将属性初始化为函数?下面的这段导致解析错误:语法错误,意想不到的T_FUNCTION使用匿名函数初始化类属性

<?php 
    class AssignAnonFunction { 
    private $someFunc = function() { 
     echo "Will Not work"; 
    }; 
    } 
?> 

然而,你可以将属性初始化字符串,数字或其他数据类型?

编辑:

但我可以指定一个函数在__construct()方法的属性。以下工作:

<?php 
    class AssignAnonFunctionInConstructor { 
    private $someFunc; 

    public function __construct() { 
     $this->someFunc = function() { 
     echo "Does Work"; 
     }; 
    } 
    } 
?> 

回答

18

因为它没有在PHP中实现。

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

They (properties) 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.

你不能初始化像这样的属性,函数不是常量值。因此我原来的回答是“它没有实施”。

为什么不实施?我只能猜测 - 这可能是一项相当复杂的任务,没有人加紧实施它。和/或可能没有足够的需求这样的功能。

+0

没有帮助或信息;为什么没有实施的背景是什么? – Ophidian 2009-10-27 19:27:05

+2

批评是当之无愧的,我改变了答案,略有更多的细节。 – 2009-10-27 20:08:07

2

在PHP 5.3(最新版本)之前,闭包不存在于PHP中。确保你有PHP 5.3如果你想这样做。

在早期版本中,您可以排序与create_function()函数复制此功能,有点像这样:

$someFunc = create_function($args,$code); 
$someFunc(); 

其中的$ args是格式化的,如“$ X,$ Y,$ Z A字符串“和$ code是你的PHP代码的字符串。

+0

这是在PHP 5.3中。我用一个可行的案例更新了我的问题(我可以在php中使用__construct魔术方法将属性赋值给一个属性) – 2009-10-27 19:50:06

+0

OP中的语法不起作用,create_function()不是一回事 – 2015-07-26 14:22:03