PHP equivalent of JavaScript bind -


first excuse english i'm not native speaker , sorry if looks rough, first time post on site. problem quite simple think. let's say, have :

class {      function foo() {          function bar ($arg){             echo $this->baz, $arg;         }          bar("world !");      }      protected $baz = "hello ";  }  $qux = new a;  $qux->foo(); 

in example, "$this" doesn't refer object "$qux".

how should make reffer "$qux"?

as might in javascript : bar.bind(this, "world !")

php doesn't have nested functions, in example bar global. can achieve want using closures (=anonymous functions), support binding of php 5.4:

class {     function foo() {         $bar = function($arg) {             echo $this->baz, $arg;         };         $bar->bindto($this);         $bar("world !");     }     protected $baz = "hello "; }  $qux = new a; $qux->foo(); 

upd: however, bindto($this) doesn't make sense, because closures automatically inherit this context (again, in 5.4). example can simply:

    function foo() {         $bar = function($arg) {             echo $this->baz, $arg;         };         $bar("world !");     } 

upd2: php 5.3- seems possible ugly hack this:

class {     function foo() {         $me = (object) get_object_vars($this);         $bar = function($arg) use($me) {             echo $me->baz, $arg;         };         $bar("world !");     }     protected $baz = "hello "; } 

here get_object_vars() used "publish" protected/private properties make them accessible within closure.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -