【问题标题】:Is it possible to "escape" a method name in PHP, to be able to have a method name that clashes with a reserved keyword?是否可以在 PHP 中“转义”方法名称,以便能够拥有与保留关键字冲突的方法名称?
【发布时间】:2010-02-20 16:09:33
【问题描述】:

我在 PHP 中做 MVC,我想在我的控制器中有一个 list() 方法,拥有 URL /entity/list/parent_id,以显示属于该父级的所有“x” .

但是,我不能有一个名为 list() 的方法,因为它是 PHP 保留关键字。

例如,在 VB.Net 中,如果我需要一些名称与保留关键字冲突的东西,我可以将其包装在 [reserved_name] 中。
在 SQL 中,您可以做同样的事情。
在 MySQL 中,您使用反引号 `

PHP 中是否有一些语法指定“将其视为标识符,而不是关键字”?

(注意:我知道我可以在没有 list() 方法的情况下使用路由来执行此操作。我也可以简单地将操作称为其他内容。问题是 PHP 是否提供这种转义)

【问题讨论】:

    标签: php escaping keyword identifier reserved-words


    【解决方案1】:

    您可以使用__call() 方法来调用实现您的功能的私有或公共_list() 方法。

    /**
     * This line for code assistance
     * @method  array list() list($par1, $par2) Returns list of something. 
     */
    class Foo 
    {
        public function __call($name, $args) 
        {
            if ($name == 'list') {
                return call_user_func_array(array($this, '_list'), $args);
            }
            throw new Exception('Unknown method ' . $name . ' in class ' . get_class($this));
        }
    
        private function _list($par1, $par2, ...)
        {
            //your implementation here
            return array();
        }
    }
    

    【讨论】:

      【解决方案2】:

      对于变量名,您可以使用括号符号:

      ${'array'} = "test";
      echo ${'array'};
      

      但是 PHP 没有提供转义函数名的方法。

      如果您想要一种“用户定义”的解决方法,请查看此评论:

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

      【讨论】:

      • 谢谢!那篇 PHP.net 文章指出了这一点。不幸的是,它不适用于 CakePHP,它可能会枚举 Controller 的所有方法,而不是仅仅尝试调用它。哦,好吧,去寻找要列出的同义词:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多