Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Variable Function Array Value

Tags:

arrays

php

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?

like image 804
AdmiralSpeedy Avatar asked Oct 14 '16 03:10

AdmiralSpeedy


People also ask

How do you get the value of an array from a function?

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.

How do you get a specific value from an array in PHP?

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.

What is variable [] in PHP?

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.

Can PHP function return multiple values?

A function can not return multiple values, but similar results can be obtained by returning an array.


1 Answers

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.
like image 148
BlitZ Avatar answered Oct 29 '22 13:10

BlitZ