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.
source share