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

553

I'm doing MVC in PHP, and i'd like to have a list() method inside my Controller, to have the URL /entity/list/parent_id, to show all the "x" that belong to that parent.

However, I can't have a method called list(), since it's a PHP reserved keyword.

In VB.Net, for example, if I need to have something with a name that clashes with a reserved keyword, I can wrap it in [reserved_name].
In SQL, you can do the same thing.
In MySQL, you use the backtick `

Is there some syntax in PHP that specifies "treat this as an identifier, not as a keyword"?

(NOTE: I know I can use routes to do this without having a list() method. I can also simply call the action something else. The question is whether PHP provides this kind of escaping)

704

Answer

Solution:

You can use__call() method to invoke private or public_list() method which implements your functionality.

/**
 * 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();
    }
}
862

Answer

Solution:

With variable names you can use the bracket signs:

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

But PHP does not provide a method for escaping function names.

If you want a 'user-defined' way of getting around this, check out this comment:

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

People are also looking for solutions to the problem: javascript - Get multiple PHP arrays within Ajax and create DIV tags

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.