我可以为我的函数和类使用PHP保留名吗?

时间:2011-03-14 12:21:49

标签: php class function reserved

我想创建一个名为“new”的函数和一个名为“case”的类。

我能用PHP做到吗?

6 个答案:

答案 0 :(得分:28)

Noyou can't。感谢上帝。

答案 1 :(得分:23)

实际上,虽然定义这样的方法会导致解析错误,但使用它不会,这允许某种变通方法:

class A {
    function __call($method, $args) {
        if ($method == 'new') {
            // ...
        }
    }
}

$a = new A;
$a->new(); // works!

可追溯至2004年的相关feature request仍然开放。

2016年1月编辑

从PHP 7开始,现在可以使用目前受限制的关键字为您的方法命名,这归功于Context Sensitive Lexer

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

但是,你仍然无法为你的班级Case命名。我很害怕。

答案 2 :(得分:2)

你不能这样做,另一种选择是只使用_case()或_new()作为函数名称

同时退房:

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

答案 3 :(得分:1)

默认情况下,它是不可能的,它们是保留字,你不能使用它们。

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

可能你可以重新编译PHP或类似的东西来实现你的目标,但我认为(正如其他人回答你)这不是一个好主意:)

HTH!

答案 4 :(得分:0)

按照本杰明所提到的,在Array.prototype.map(),第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);
    }
}

答案 5 :(得分:0)

我刚刚重命名了课程,以解决我的问题。

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