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?
Yes, you can: $array = array( 'func' => function($var) { return $var * 2; }, ); var_dump($array['func'](2)); This does, of course, require PHP anonymous function support, which arrived with PHP version 5.3. 0.
1. PHP array_search() function. The PHP array_search() is an inbuilt function that is widely used to search and locate a specific value in the given array. If it successfully finds the specific value, it returns its corresponding key value.
Variable is a symbol or name that stands for a value. Variables are used for storing values such as numeric values, characters, character strings, or memory addresses so that they can be used in any part of the program. Declaring PHP variables.
A function can not return multiple values, but similar results can be obtained by returning an array.
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:
$request[2]
(is it really a string?).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With