2015-07-15 3 views
0

следующий код, который не работает, как и ожидалось, более точные комментарии ниже в кодеобласть методов частного класса в анонимной функции

class A1 { 
    function __call($name, $arguments) { 
     throw new \Exception('Method ..... ' . $name . ' not exists ...'); 
    } 

    /* When this method is public - it works good*/ 
    private function test($d) { 
     var_dump($d); 
    } 

    public function test1() { 
     /* duplicate for using in anonym function */ 
     $_this=$this; 

     #$_this->test(1); #- it works good!!! 
     #var_dump($_this); 

     /* create anonym func, wherein the method is called test() */ 
     $rrr= function()use($_this){ 
      #var_dump($_this); # - values of output equally with above used var_dump 
      $_this->test(1); # - it do NOT WORK !!!! 
     }; 

     $rrr(); # catch Exception of __call() ... 
    } 
} 

$r = new A1; 
var_dump($r->test1()); 

Я не могу понять, почему счетчики анонимных вызовов функции, как из ВНЕШНИЕ, когда $ это не изменено ...

ошибка?

ответ

1

Поскольку $this не существует, когда класс скомпилирован (только при его создании), он не может быть передан через use; Вы должны связать $this к вашему закрытию во время выполнения:

class A1 { 
    function __call($name, $arguments) { 
     throw new \Exception('Method ..... ' . $name . ' not exists ...'); 
    } 

    /* When this method is public - it works good*/ 
    private function test($d) { 
     var_dump($d); 
    } 

    public function test1() { 
     /* create anonym func, wherein the method is called test() */ 
     $rrr= function(){ 
      $this->test(1); 
     }; 
     Closure::bind($rrr, $this); 
     $rrr(); # catch Exception of __call() ... 
    } 
} 

$r = new A1; 
$r->test1(); 

Demo

или передать его в качестве времени выполнения аргумента, а не use аргумента:

class A1 { 
    function __call($name, $arguments) { 
     throw new \Exception('Method ..... ' . $name . ' not exists ...'); 
    } 

    /* When this method is public - it works good*/ 
    private function test($d) { 
     var_dump($d); 
    } 

    public function test1() { 
     /* create anonym func, wherein the method is called test() */ 
     $rrr= function($this){ 
      $this->test(1); 
     }; 
     $rrr(); # catch Exception of __call() ... 
    } 
} 

$r = new A1; 
$r->test1(); 

Demo

+0

Марк Бейкер, спасибо! это работает! но он должен был обновить систему и версию php, но это мелочи) – Dmitriy

Смежные вопросы