16

I can't seem to find anything of this, and was wondering if it's possible to store a function or function reference as a value for an array element. For e.g.

array("someFunc" => &x(), "anotherFunc" => $this->anotherFunc())

Thanks!

2
  • 1
    Possible duplicate of Can you store a function in a PHP array? Commented Nov 11, 2015 at 11:29
  • x() is not a function or a reference to a function but a function call; i.e. the function is executed right now and the value it returns is stored in your array at key 'someFunc'. Read the PHP documentation about functions for more information (including the answer to your question). Commented Nov 11, 2015 at 11:37

5 Answers 5

15

You can "reference" any function. A function reference is not a reference in the sense of "address in memory" or something. It's merely the name of the function.

<?php

$functions = array(
  'regular' => 'strlen',
  'class_function' => array('ClassName', 'functionName'),
  'object_method' => array($object, 'methodName'),
  'closure' => function($foo) {
    return $foo;
  },
);

// while this works
$functions['regular']();
// this doesn't
$functions['class_function']();

// to make this work across the board, you'll need either
call_user_func($functions['object_method'], $arg1, $arg2, $arg3);
// or
call_user_func_array($functions['object_method'], array($arg1, $arg2, $arg3));
Sign up to request clarification or add additional context in comments.

3 Comments

Okay, thanks! So ultimately, I suppose I'm looking for a means for creating a pointer. I don't want to duplicate a function, but merely want a pointer to it such that I can modify and read the value to which the pointer refers.
Damn, just realized that call_user_func was an actual member of PHP's function-method library! Thanks!
@Wasim maybe should try a more "current" PHP version. 5.3 or above
5

PHP supports the concept of variable functions, so you can do something like this:

function foo() { echo "bar"; }
$array = array('fun' => 'foo');
$array['fun']();

Yout can check more examples in manual.

1 Comment

Thanks, was thinking of doing that as a solution. But the docs also states that an element's value can be of any type, so why can't functions be used? I can use "element"=>object(), but don't know of what can be done with this.
5

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. This is going to leave you with quite unreadable code though.

7 Comments

That doesn't work for me, it returns UNEXPECTED T_FUNCTION error.
What version of PHP are you using? It runs fine on my laptop, which is running PHP 5.3.6. If you are using 5.2 then this will definitely not work as mentioned in my answer above.
Ah, okay. That's probably why. I'm using PHPDesigner2008, so it's error notification library is probably outdated.
Yeah that is why I couldn't post a link to a work example on codepad.org. It must be running an older version of PHP.
Well the decision if this is unreadable or not should be left to the observer
|
5

check out PHP's call_user_func. consider the below example.

consider two functions

function a($param)
{
    return $param;
}

function b($param)
{
    return $param;
}


$array = array('a' => 'first function param', 'b' => 'second function param');

now if you want to execute all the function in a sequence you can do it with a loop.

foreach($array as $functionName => $param) {
    call_user_func($functioName, $param);
}

plus array can hold any data type, be it function call, nested arrays, object, string, integer etc. etc.

1 Comment

I just want to add that this is a nice way to replace a long switch statement when you don't want your methods to get overly complex.
-1

this is how I would approach it

     // function example:
     function someFunction() {
        return "This text comes from a function";
      }     
      // create arr
    $myArr = array("some text", 15, ["sub array item 1", "sub array item 2"], someFunction());

    // calling the function from the array item:  
    echo $myArr[0];
    echo "<br>";
    echo $myArr[1];
    echo "<br>";
    echo $myArr[2][1];
    echo "<br>";
    echo $myArr[3];

This would be the output:-
Output:-
some text
15
sub array item 2
This text comes from a function

1 Comment

This stores the return value of the function (a string) in the array, which is not what the question is asking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.