我很嫉妒Ruby,他們使用「new」作爲方法。是否有可能在PHP 5.3中使用名稱空間來實現這一點?在PHP 5.3中可以使用new作爲方法名嗎?
class Foo
{
public function new()
{
echo 'Hello';
}
}
我很嫉妒Ruby,他們使用「new」作爲方法。是否有可能在PHP 5.3中使用名稱空間來實現這一點?在PHP 5.3中可以使用new作爲方法名嗎?
class Foo
{
public function new()
{
echo 'Hello';
}
}
否。像其他地方已經指出的那樣,new
是保留關鍵字。試圖將其用作方法名稱將導致出現分析錯誤:「語法錯誤,意外T_NEW
,預計T_STRING
」。命名空間不起作用,因爲new
關鍵字適用於任何名稱空間。唯一的解決方法是通過虛擬方法,例如,
/**
* @method String new new($args) returns $args
*/
class Foo
{
protected function _new($args)
{
return $args;
}
public function __call($method, $args)
{
if($method === 'new') {
return call_user_func_array(array($this, '_new'), $args);
} else {
throw new LogicException('Unknown method');
}
}
}
$foo = new Foo;
echo $foo->new('hello'); // return hello
echo $foo->boo(); // throws Exception
但我會勸阻這一點。所有魔術方法都比直接調用方法慢,如果簡單的規則是可能沒有方法名稱new
,那麼就是它。使用同義詞。
感謝您的建議。雖然我愛新。啊。也許我會用create來代替。 – Emil 2010-11-27 13:16:41
,你可以看到here,「新」是保留字就行了,所以你不能用它來命名的方法。
You cannot use any of the following words as constants, class names, function or method names
那麼簡單的答案似乎是沒有,因爲它是一個reserved keyword。
在這樣的課程中有這樣的課程會很好,但保留字是重要的原因。人們傾向於使用其他同義詞來代替:創建,新建,getInstance()[通常是靜態用法]等。
是的,從PHP7開始。但只限於類內,界面和特徵。
Globally reserved words as property, constant, and method names within classes, interfaces, and traits are now allowed. ...
是否@new()爲你工作? – 2010-11-27 12:20:29