2011-02-26 20 views
1
class Foo 
{ 

const MY_CONST = 'this is ' . 'data' ; //use of concatenation 

public function __construct() {} 

} 

這給出錯誤:起爆/聲明在PHP類常量與級聯

語法錯誤,意想不到的, 期待 ' '或 ';''。'

那麼我應該如何使用與常量串接?

回答

1

常量,應該是常數,這就是爲什麼你不能在這裏使用表達式。

我不建議你runkit_constant_add(),因爲它會變換一個常量在一個變量(或種類)中,而這種情況並非如此,可能會造成混淆。

要解決此問題,我通常將我的常量「包裝」在受保護的數組中。 使用該常量可以使用數組的一個鍵,以獲得更復雜的表達式。

class Foo { 
    const YEAR = 'year'; 
    const DAYS = 'days'; 

    protected $_templates = array(
     self::YEAR => 'There is %s' . 'year ago', 
     self::DAYS => 'There are ' . '%s' . 'days ago', 
    ); 

    public function getMessage($key) 
    { 
     return $this->_templates[$key]; 
    } 
} 

,讓你使用:

$foo = new Foo(); 
$foo->getMessage(Foo::YEAR); 
+0

這是一個很好的解決方法謝謝花時間回答。 – 2011-02-26 09:30:47

3

您不能在那裏指定表達式。您只能在類定義中定義普通值。

唯一的解決方法是在構造函數中使用runkit_constant_add(),這在所有PHP設置中都不可用。

+0

清潔的方式,但不是因爲這個擴展的便攜式解決方案默認情況下不啓用。感謝您花時間回答。 – 2011-02-26 09:33:10