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

后端 未结 6 608
时光说笑
时光说笑 2020-11-28 15:50

I\'d like to create a function called \"new\" and a class called \"case\".

Can I do that in PHP?

6条回答
  •  伪装坚强ぢ
    2020-11-28 16:29

    Actually, while defining such a method results in a parse error, using it does not, which allows some kind of workarounds:

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

    A related feature request dating back to 2004 is still open.

    Edit January 2016

    As of PHP 7, it is now possible to name your methods using keywords that were restricted so far, thanks to the Context Sensitive Lexer:

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

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

提交回复
热议问题