Is it possible to use new as a method name in 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 开发者_JS百科the use of namespaces?
class Foo
{
public function new()
{
echo 'Hello';
}
}
as you can see here, "new" is on the list of the reserved words, so you cannot use it to name a method.
You cannot use any of the following words as constants, class names, function or method names
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
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.
Well the short answer to that appears to be no, as it is a reserved keyword.
It would be nice to have available in classes like that, but reserved words are important for a reason. People tend to use other synonyms instead: create, new, getInstance() [usually static usage], etc.
Yes, as of PHP7. But only within classees, interfaces and traits.
Globally reserved words as property, constant, and method names within classes, interfaces, and traits are now allowed. ...
-- http://php.net/manual/en/migration70.other-changes.php#migration70.other-changes.loosening-reserved-words
精彩评论