Ahmed Saber
Ahmed Saber

Reputation: 509

Call function from an object?

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

I get this error Call to undefined method

Upvotes: 5

Views: 1157

Answers (5)

Mukesh Soni
Mukesh Soni

Reputation: 6668

Or, just for the fun of it, you can do something like this -

<?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?"));
?>

Upvotes: 0

matino
matino

Reputation: 17735

There is no function a() but the property a, so you should call it by $ar->a.
Anyway I don't think it's going to work the way you expect it to.

EDIT: As suggested by Álvaro G. Vicario you should use call_user_func, not echo to call the function and it will work correctly.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382909

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.

Upvotes: 3

ANisus
ANisus

Reputation: 78075

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.

Upvotes: 2

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146650

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);

?>

Upvotes: 2

Related Questions