|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2014-03-02 09:03 UTC] o dot pikozh at gmail dot com
 Description:
------------
It is not clearly defined if user is allowed to name his variables '$this'.
(Yep, I know that '$this' variable has special meaning, however its usage in non-special meaning should be clarified:
- either '$this' variable can never be used in non-special meaning;
- either '$this' variable can be used in non-special meaning on
Test script:
---------------
//Assuming we have:
class TestClass {function m() {echo 'm'};}
//Case 1:
function f1($this) {$this->m();}
//This code compiles.
//Case 2:
function f2($this) {$this->m();}
f2(new TestClass);
//This code sais: 'PHP Fatal error:  Using $this when not in object context in'
//Case 3:
function f3($this) {$t = $this; $t->m();}
f3(new TestClass);
//This code compiles and says 'm'.
This is inconsistent.
Either it should fail immediately after reading 'function fN($this)' saying smth like 'Fatal error: Cannot use $this as custom variable/parameter name'.
Or it should work.
At least, cases 2 and 3 should behave identically.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 03:00:01 2025 UTC | 
IMO, just allow function parameter to be called '$this' (not in method, of course). It is useful for writing systems, which allow dynamic method addition. Like this: class User extends \MyLib\Core\DynamicallyExtendableObject { function getSurname() {...} function getName() {...} } ... User::RegisterMethod('getFullname', function($this) {return $this->getName() . ' ' . $this->getSurname();});Hmmm, I've realized that this now can be implemented even without creating explicit '$this' parameter (since PHP 5.4 supports bind/bindTo). Never-the-less, per my opinion: - Either this code should run fine: function f($this) {return $this->m;} f($someObject); - Either this code should fail: function f($this) {} //I.e. just declaring function with '$this' parameter should cause error.... but currently "function f($this) {}" (and even "function f($this) {print_r($this);} f($someObject);") runs fine, but "function f($this) {print_r($this->m);} f($someObject);" fails.