AdmiralSpeedy
AdmiralSpeedy

Reputation: 77

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?

Upvotes: 6

Views: 86

Answers (1)

BlitZ
BlitZ

Reputation: 12168

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

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

Simple enough example 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.

Upvotes: 6

Related Questions