Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function from an object?

Tags:

oop

php

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

I get this error Call to undefined method

like image 956
Ahmed Saber Avatar asked Apr 10 '12 09:04

Ahmed Saber


3 Answers

Update:

If you are using PHP 5.3 or greater, take a look at other answers please :)


I don't think that's correct syntax, it would give you:

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

You need to create a class, add method to it, use new keyword to instantiate it and then you will be able to do:

$ar->a();

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

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

See Classes and Objects for more information.

like image 148
Sarfraz Avatar answered Oct 18 '22 01:10

Sarfraz


Anonymous or not, you have a callback function, thus you need to handle it as such. E.g.:

<?php

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

call_user_func($ar->a);

?>
like image 20
Álvaro González Avatar answered Oct 18 '22 02:10

Álvaro González


For some reason it doesn't seem possibly to run the closure the way you do. If you modify your code and set another variable to the function, it can be called:

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

This is no solution. But from what I can see, this seems like a bug or limitation in PHP 5.3.

I am using 5.3.5 when trying this.

like image 34
ANisus Avatar answered Oct 18 '22 01:10

ANisus