Search the Community
Showing results for tags '$this'.
-
Hi Everyone, I am Struggling to understand the differences between "self", "$this", "::" and "->" and when / how to use them in classes. Any help would be appreciated, also if you could dumb it down to plain english that would help alot! Thanks in advance (In what I've been reading it's been saying stuff about static methods stuff and I'm not sure when / how this influences it - am I going down the wrong path?)
- 6 replies
-
- differences between
- self
-
(and 2 more)
Tagged with:
-
Consider the following code: <?php error_reporting( E_ALL | E_STRICT ); class staticClass { function staticMethod() { //when called statically from the global scope, this throws a fatal error due to $this echo $this->echoMe . "\n"; } } class dynamicClass { public $echoMe; public function __construct( $echoMe ) { $this->echoMe = $echoMe; } public function thisShouldNotWork() { //calling the staticClass method statically does NOT throw a fatal error as expected, the $this reference inside //staticClass is assumed to be a reference to the current instance of dynamicClass instead staticClass::staticMethod(); } } $a = new dynamicClass( "Hello, World!" ); $a->thisShouldNotWork(); /* The above throws a strict warning BUT STILL PRINTS "Hello, World!" Strict Standards: Non-static method staticClass::staticMethod() should not be called statically, assuming $this from incompatible context in test.php on line 22 Hello, World! */ The aptly named function thisShouldNotWork calls a method statically when that method was not defined as static. Even though the function is called statically, $this exists inside that function and can be manipulated and accessed. However, $this inside of staticClass points to a different class. No inheritance is given by the code, but one class is able to access another's variables using $this. PHP "falls back" to the last valid instance of $this since it's a super-global. Only a strict warning level will tell you that something wacky is going on.