PHP variable array variable value

I need to use variable names for the project I'm working on, but ran into some strange problem. The function name ends as a string element in the array.

It works:

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

It does not mean:

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

And I can’t understand why. It throws an array for a string conversion error, as if it ignored that I provided a key to a specific element. Is this how it works, or am I doing something wrong?

+6
source share
1 answer

As for php 5 , you can use curly syntax with bindings:

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

Simple playback example:

 <?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 strictly evaluated in order from left to right, unlike the previous combination of special cases.

There is also a table for php 5 and php 7 differences on this subject just below the quote in the docs I provided here.

What things you should consider:

  • Check the value of $request[2] (is it really a string ?).
  • Check your php version (is it php 5+ or php 7+ ?).
  • Check out the guide to function variables for your release.
+6
source

All Articles