可以在PHP 5.3中使用new作为方法名称吗? [英] Is it possible to use new as a method name in PHP 5.3?
问题描述
我嫉妒Ruby使用"new"作为方法.是否可以通过使用命名空间在PHP 5.3中实现这一目标?
I'm jealous of Ruby with their use of "new" as a method. Is it possible to achieve this in PHP 5.3 with the use of namespaces?
class Foo
{
public function new()
{
echo 'Hello';
}
}
推荐答案
否.就像在其他地方已经指出的那样,new
是保留关键字.尝试将其用作方法名称将导致解析错误:语法错误,意外的T_NEW
,期望的是T_STRING
".命名空间将无济于事,因为new
关键字适用于任何命名空间.解决此问题的唯一方法是借助虚拟方法,例如
No. Like already pointed out elsewhere, new
is a reserved keyword. Trying to use it as a method name will result in a Parse error: "syntax error, unexpected T_NEW
, expecting T_STRING
". Namespaces will not help, because the new
keyword applies to any namespace. The only way around this would be by means of a virtual method, e.g.
/**
* @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
,就可以了.使用同义词.
But I would discourage this. All magic methods are slower than direct invocation of methods and if the simple rule is there may be no method name new
, then just be it. Use a synonym.
这篇关于可以在PHP 5.3中使用new作为方法名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!