|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2011-06-12 03:53 UTC] rasmus at mindplay dot dk
 Description:
------------
$this is not generally allowed outside an object context, but sometimes it is.
I discovered this while trying to write a cheeky little base-class that would 
allow you to decorate objects with new methods, at run-time.
I would have gotten away with it, too - and I still could of course, only I would 
have to break from the convention of $this, and naming the context-object 
something else, which kind of sucks.
Test script:
---------------
<?php
$foo = function($this)
{
  var_dump($this); // this will work!
};
$foo('bar');
// now an object:
class Test
{
  public $foo = 'bar';
}
$test = new Test;
// and another closure:
$ouch = function($this)
{
  var_dump($this->bar); // this will blow up
};
$ouch($test);
Expected result:
----------------
The two examples should either fail consistently, or succeed consistently.
From my point of view, why should I not be allowed to have a local variable named 
$this if I wanted to? There's nothing special or magical about this variable, 
besides the fact that it gets automatically assigned on call.
Actual result:
--------------
The second example fails.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 20:00:01 2025 UTC | 
Note, the closure and creation of another object instance are irrelevant. Two simpler reproduction scripts -- one uses anonymous function, the other plain function. <?php $foo = function($this) { var_dump($this); // this will work! var_dump($this->bar); // this will blow up }; $foo(new stdclass); ?> <?php function bar($this) { var_dump($this); // this will work! var_dump($this->bar); // this will blow up } bar(new stdclass); ?> Expected result: both uses of $this and $this->bar behave in similar way. Actual result: PHP complains only on $this->bar.