Created
October 10, 2012 20:30
-
-
Save kojiromike/3868227 to your computer and use it in GitHub Desktop.
PHP closures of $this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Apparently this is fixed in php 5.4 | |
$ php -a | |
Interactive shell | |
php > /** | |
/* > * Demonstrate that you can use $this to refer to a member variable / property. | |
/* > */ | |
php > class NullHypothesis { | |
php { function foo() { | |
php { $this->x = 123; | |
php { return $this->x; | |
php { } | |
php { } | |
php > echo 'Null: '; | |
Null: | |
php > $a = new NullHypothesis(); | |
php > echo "x{$a->foo()}x\n"; | |
x123x | |
php > /** | |
/* > * Demonstrate that you can use $this in an anonymous function inside a method. | |
/* > */ | |
php > class ThisImplicitClosure { | |
php { function foo() { | |
php { $this->x = 123; | |
php { $f = function () { return $this->x; }; | |
php { return $f(); | |
php { } | |
php { } | |
php > echo 'Implicit: '; | |
Implicit: | |
php > $b = new ThisImplicitClosure(); | |
php > echo "x{$b->foo()}x\n"; | |
Fatal error: Using $this when not in object context in php shell code on line 4 | |
$ php -a | |
Interactive shell | |
php > /** | |
/* > * Demonstrate that you can use $this in an explicit closure inside a method. | |
/* > */ | |
php > class ThisExplicitClosure { | |
php { function foo() { | |
php { $this->x = 123; | |
php { $f = function () use ($this) { return $this->x; }; | |
php { return $f(); | |
php { } | |
php { } | |
Fatal error: Cannot use $this as lexical variable in php shell code on line 4 | |
$ php -a | |
Interactive shell | |
php > /** | |
/* > * Demonstrate that you can work around PHP being obtuse. | |
/* > */ | |
php > class ThisSucks { | |
php { function foo() { | |
php { $this->x = 123; | |
php { $self = $this; | |
php { $f = function () use ($self) { return $self->x; }; | |
php { return $f(); | |
php { } | |
php { } | |
php > echo 'Suck: '; | |
Suck: | |
php > $d = new ThisSucks(); | |
php > echo "x{$d->foo()}x\n"; | |
x123x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment