Call a function from an object?

<?php
$ar = (object) array('a'=>function(){
   echo 'TEST';
});
$ar->a();
?>

I get this error Undefined method call

+5
source share
5 answers

Anonymous or not, you have a callback function, so you need to handle it as such. For instance:.

<?php

$ar = (object) array(
    'a' => function(){
        echo 'TEST';
    }
);

call_user_func($ar->a);

?>
+2
source

Update:

If you are using PHP 5.3 or higher, see other answers, please :)


I don't think the correct syntax is, this will give you:

Parse error: syntax error, unexpected T_FUNCTION in....

You need to create a class, add a method to it, use the keyword newto create it, and then you can:

$ar->a();

class myclass
{
    public function a()
    {
        echo 'TEST';
    }
}

$ar = new myclass;
$ar->a(); // TEST

See Classes and objects for more details .

+3
source

- , , , . , :

$ar = (object) array('a'=>function(){
   echo 'TEST';
});
$a = $ar->a;
$a();

. , , PHP 5.3.

5.3.5 .

+2

a(), a, $ar->a.
, , , .

EDIT: Álvaro G. Vicario, call_user_func, echo, , .

0

, , - -

<?php
$ar = new stdClass;
$ar->a = function($to_echo){ echo $to_echo; };
$temp = $ar->a;

//[Edit] - $ar->a("hello"); // doesn't work! php tries to match an instance method called     "func" that is not defined in the original class' signature
$temp("Hey there");
call_user_func($ar->a("You still there?"));
?>
0

All Articles