PHP has no nested functions, so in your example bar is essentially global. You can achieve what you want by using closure (= anonymous functions) that support binding with PHP 5.4:
class A { 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 much sense because closing will automatically inherit this from the context (again, in 5.4). So your example could be simple:
function foo() { $bar = function($arg) { echo $this->baz, $arg; }; $bar("world !"); }
UPD2: for php 5.3 - this seems possible only with an ugly hack:
class A { 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 to βpublishβ protected / private properties to make them available within the closure.
georg source share