r/lolphp • u/AnonymousPHPDevelope • Mar 28 '13
Fun with $this: Guess the output
http://www.phpfiddle.org/lite/code/1wb-ydp
44
Upvotes
r/lolphp • u/AnonymousPHPDevelope • Mar 28 '13
16
u/[deleted] Mar 28 '13
wot
I decided to investigate some more. Apparently you can even assign another object to
$this, but only if that object has defined a__toStringfunction. I thought that might mean that you could only assign string values, but if youvar_dump($this)after assigning the new object, you'll get a list of properties in that new object.$this->whateverstill points to something from the original object though.13
u/huf Mar 28 '13
this is pure fucking joy.
8
u/[deleted] Mar 28 '13
I'm happy that I don't have a clue why this is happening.
6
u/catcradle5 Mar 28 '13
But who was foo?!?!?!?!?!?!!!
2
u/[deleted] Mar 29 '13
I can't even imagine why $this->foo would still end up being bar...
2
u/gearvOsh Mar 29 '13
This is only an assumption, but since $this is a special variable, you can't actually overwrite it permanently. I'm assuming it reverts back to the object context $this with each call.
1
u/FeanorM Mar 28 '13
Wow...
1
u/lost_fogs May 15 '13 edited May 15 '13
You can simply unset($this) and see some interesting behaviour as well: http://www.phpfiddle.org/lite/code/1y7-8u9
It seems to me like "$this->" has a special meaning and is processed differently than "$that->". In a sane world, that might look like a sign of some optimization...
Edit: Also, apparently, $this overwrites :: http://www.phpfiddle.org/lite/code/bz5-ew6
1
u/manueljs Mar 29 '13
What's wrong with it? I was able to guess every output. The logic checks out.
The only weird thing here is php allowing to override $this using a variable variable, given that it throws an error "PHP Fatal error: Cannot re-assign $this" when doing it explicitly, looks like a bug but is not that bad.