user1377362 user1377362 - 1 month ago 7
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];
$pages->$func();


This doesn't:

$pages->$request[2]();


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?

Answer

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

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

Simple enough examlpe to reproduce:

<?php

$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];
$pages->$methodName();

Quote from php.net 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.