Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
up vote 5 down vote accepted

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.
share|improve this answer
    
Thank you! I was looking for documentation covering this and couldn't find it. I'll accept your answer as soon as the timer lets me. – user1377362 Oct 14 at 3:20
1  
Beat me too it, +1 Could also ( maybe ? ) use ReflectionFunction class and invoke, but it's a bit overkill for this. php.net/manual/en/class.reflectionfunction.php – ArtisticPhoenix Oct 14 at 3:27
    
@ArtisticPhoenix yeah, there is also call_user_func(). Still, I believe, that this question is about syntax more, than about solution to a problem. – Num6 Oct 14 at 3:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.