Can I use PHP reserved names for my functions and classes?

I would like to create a function called "new" and a class of "case".

Can I do this in PHP?

+11
source share
6 answers

No , you cannot . Thank God.

+28
source

Actually, when defining such a method, a parsing error occurs, its use is not performed, which allows you to use some workarounds:

class A { function __call($method, $args) { if ($method == 'new') { // ... } } } $a = new A; $a->new(); // works! 

The relative feature request for 2004 is still open.

Edit January 2016

Starting with PHP 7, it is now possible to name your methods using keywords that have been limited so far, thanks to Context Sensitive Lexer :

 class Foo { public function new() {} public function list() {} public function foreach() {} } 

You still can't name the Case class, I'm afraid.

+22
source

You cannot do this, an alternative is to simply use _case () or _new () as function names

Also check:

Is escape possible? PHP method name to have a method name that encounters a reserved keyword?

+2
source

By default, this is not possible, these are reserved words, and you cannot use them.

http://www.php.net/manual/en/reserved.keywords.php

Maybe you can recompile PHP or something similar to achieve your goal, but I think (like the other people who answered you) that this is not a good idea :)

NTN!

+1
source

According to what Benjamin mentioned, the use of "clone", (which is reserved), line 545, is interesting in this class.

  public function __call($method, $args) { if ('clone' == $method) { return call_user_func_array(array($this, 'cloneRepository'), $args); } else { $class = get_called_class(); $message = "Call to undefined method $class::$method()"; throw new \BadMethodCallException($message); } } 
0
source

I just renamed the class to overcome my problem.

 foreach($array as $key => $line){ if($key == "resource"){ $key = "resources"; $array->$key = $line; } } 
0
source

All Articles