2009-10-27 55 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