user1377362 user1377362 - 12 days ago 4x
PHP Question

PHP Variable Function Array Value

I need to use variable function names for a project I'm working on but have run into a bit of strange issue. The function name ends up as a string element in an array.

This works:

$func = $request[2];

This doesn't:


And I can't figure out why. It throws an array to string conversion error, as if it's ignoring that I have supplied a key to a specific element. Is this just how it works or am I doing something wrong?


As for php 5, you can use curly-braced syntax:


Simple enough examlpe to reproduce:


$request = [
    2 => 'test'

class Pages
    function test()
        return 1;

$pages = new Pages();

echo $pages->{$request[2]}();

Alternatively (as you noted in the question):

$methodName = $request[2];

Quote from for php 7 case:

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases.

Also there is a table for php 5 and php 7 differences for this matter just below quote in the docs I've supplied here.

Which things you should consider:

  • Check value of the $request[2] (is it really a string?).
  • Check your version of php (is it php 5+ or php 7+?).
  • Check manual on variable functions for your release.