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

后端 未结 6 584
时光说笑
时光说笑 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:15

    No, you can't. Thank god.

    0 讨论(0)
  • 2020-11-28 16:20

    Along the lines of what Benjamin mentioned, there is an interesting use of "clone", (which is reserved) in this class, line 545

     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 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 16:30

    I just renamed the class to over come my problem.

    foreach($array as $key => $line){
        if($key == "resource"){
            $key = "resources";
            $array->$key = $line;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 16:35

    You can't do that, an alternative option is to just use _case() or _new() as the function names

    Also check out:

    Is it possible to "escape" a method name in PHP, to be able to have a method name that clashes with a reserved keyword?

    0 讨论(0)
  • 2020-11-28 16:38

    By default it is not possible, they are reserved words and you can't use them.

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

    May be you can recompile PHP or something like this to achieve your aim, but I think (as the other people that answered you) that it is not a good idea :)

    HTH!

    0 讨论(0)
提交回复
热议问题