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

I get this error Call to undefined method

Ahmed Saber
  • 489
  • 1
  • 9
  • 21

5 Answers5

3

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.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • But I try Ahmed Saber is trying to use a closure function instead of declaring the class the way you do. – ANisus Apr 10 '12 at 09:55
  • @ANisus: It looks so but even that would result in `Fatal error: Call to undefined method stdClass::a()`. @Mukesh has provided an answer below, let's see if this is what he is looking for :) – Sarfraz Apr 10 '12 at 09:59
2

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

?>
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
2

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.

ANisus
  • 74,460
  • 29
  • 162
  • 158
0

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.

matino
  • 17,199
  • 8
  • 49
  • 58
0

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?"));
?>
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37