|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-10-02 15:24 UTC] ircmaxell at yahoo dot com
Description:
------------
When calling a non-static method statically from within another class (non-
inherited), $this is populated with the other object's class.
Test script:
---------------
class test1 {
public function getName() {
return $this->name;
}
}
class test2 {
public $name = 'foo';
public function getName() {
return test1::getName();
}
}
$obj = new Test2;
echo $obj->getName();
Expected result:
----------------
Fatal Error: Using $this when not in object context
Actual result:
--------------
"foo" is outputted.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 03 09:00:01 2025 UTC |
Close it if you wish, but I do honestly believe this is a major bug... This means that you cannot trust that $this is an instance of the class it's used in. So does that mean that we must add: ($this instanceof self) or throw new Exception('called from another class'); to all of our methods? Remember, any sufficiently advanced bug is indistinguishable from a feature (no matter if it is documented or not). But don't be afraid to call it what it really is... Just because it's documented, doesn't mean it isn't a bug... Again, IMHO...@ircmaxell: No, you don't need to modify all your code and add that line. Or at least you don't need to do so if you don't already have this line in every method: if (!isset($this)) throw new LogicException('Called non-static method statically'); In PHP you can't rely on $this being set. But still you do, because an unset $this is a real edge case. But I still do think that this feature *is* a bug and shall be removed. It is absolutely illogical that $this isn't instanceof self.