0

I am trying to call a PHP function via an array like so:

$x = (object) array(
    "one" => "value",
    "two" => "value2",
    "three" => function() {
        return "return_value";
    }
);

echo($x->three());

From this I receive the error:

<b>Fatal error</b>:  Call to undefined method stdClass::three()

I've searched a bit and cannot find any documentation on this, however I ran this through

php -l filename.php

which found no syntax errors.

I would like to know if what I'm trying to do is possible (end goal is to call a function with parameters from an array). Is anybody able to shed some light on this?

Thanks

Note, I have also tried:

function foo() {
    return "bar";
}
$x = (object) array(
    "foo" => foo
);
...

which leads to the same result.

2 Answers 2

3

Use an array instead of an object:

$x = array(
    "one" => "value",
    "two" => "value2",
    "three" => function() {
        return "return_value";
    }
);

To call the lambda function, you can do:

echo $x['three']();

Demo


If you really must use an object, then you can do the following:

$x = array(
    "one" => "value",
    "two" => "value2",
);

$obj = (object) $x;
$obj->three = function() {
    return "return_value";
};

To call the function:

echo $obj->three->__invoke();

Demo

Sign up to request clarification or add additional context in comments.

Comments

2

The type of method you created is classified as an anonymous function and is represented by the Closure class and thus inherits its properties, which includes the invoke method as specified by Amal Murali.

You have two ways of calling this function:

  1. echo $x->three->__invoke();
  2. echo call_user_func( $x->three );

If you need to pass arguments, you can call $x->three->__invoke( $args ); or call_user_func( $x->three, $args1, $args2 );.

Comments

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.