2

How do I define a function within a class and method is empty, method would change the calling class (as delegate in c#) The following error codes are:

class myclass{
      public $num1=0;
      public function func($a,$b);
}
$c=new myclass();
$c->func=function($a,$b){
      return $a+$b;
}
$c->func(4,8);// is error
Kara
  • 6,115
  • 16
  • 50
  • 57
jvd
  • 150
  • 1
  • 7
  • I think this would help you out http://stackoverflow.com/questions/48570/something-like-a-callback-delegate-function-in-php – Ma'moon Al-Akash Mar 23 '14 at 09:46
  • In PHP there are callbacks (same as delegates in C#) - [callback](http://www.php.net/manual/en/language.types.callable.php) – jurajvt Mar 23 '14 at 09:52

1 Answers1

1

You can do something like this:

class myclass {
      public $num1=0;
      public function func($a,$b,$fn) {
            return $fn($a,$b); // return anonymous function
      }
}

$c = new myclass();

$c->func(2,5,function($a,$b) { // declaring anonymous function with $a and $b parameters
    echo $a + $b; // result 7
});

DEMO

nanobash
  • 5,419
  • 7
  • 38
  • 56