10/20/2015

[php] 實作callback


用名稱呼
function run1($callback)
{
 $callback('123');
}

function funA($val)
{
 echo 'funA:'.$val;
}

run1('by run1');//funA:by run1

用物件傳(推薦)
class ClassB
{
 public function funB($val){
  echo 'ClassB:funB:'.$val;
 }
}

function run2(ClassB $callable){
 $callable->funB('by run2');
}

run2(new ClassB());//ClassB:funB:by run2

沒有留言:

張貼留言