Page 1 of 1
use of $this outside of class definition
Posted: Mon Mar 30, 2009 11:06 pm
by cdhiren
does anyone know usage of "$this->" outside of a class definition.
e.g: main.php
<?php
switch($this->mSubModule)
?>
without creating any object, what could be the significance of above code? i want to understand the flow.
i have the above piece of code written by some other developer but could figure out how is it possible to access class members without instantiating the object
thanks in advance.
regards
dhiren
Re: use of $this outside of class definition
Posted: Mon Mar 30, 2009 11:50 pm
by requinix
cdhiren wrote:i have the above piece of code written by some other developer but could figure out how is it possible to access class members without instantiating the object
Well, it's not possible. You can't access something that doesn't exist.
That code does not make sense unless it is used inside of a class function. In fact, besides not making sense, it's not even possible: even attempt to name a variable "this" and you'll get an "not in object context" or "cannot reassign" error.
Re: use of $this outside of class definition
Posted: Tue Mar 31, 2009 12:13 am
by cdhiren
thanks avatar. thats exactly what even i thought off. but somehow this piece of code is working. can i have your email so that i could provide the source details ...
thanks
dhiren
Re: use of $this outside of class definition
Posted: Tue Mar 31, 2009 12:18 am
by Benjamin
cdhiren wrote:somehow this piece of code is working. can i have your email so that i could provide the source details ...
It's not working. Also, we really don't provide private support here. Feel free to post your code, using the approriate code tags.
Re: use of $this outside of class definition
Posted: Tue Mar 31, 2009 1:53 am
by Chris Corbyn
cdhiren wrote:thanks avatar. thats exactly what even i thought off. but somehow this piece of code is working. can i have your email so that i could provide the source details ...
thanks
dhiren
Is this inside a template by any chance? Any file that is included by a class has access to $this:
MyClass.php
Code: Select all
<?php
class MyClass {
public $myVar;
public function setMyVar($value) {
$this->myVar = $value;
}
public function dump() {
include 'other-file.php';
}
}
other-file.php
Code: Select all
<?php
printf("\$this->myVar = %s<br />\n", $this->myVar);
So if you were to create an instance of MyClass and call setMyVar() and then dump() you'd be giving the included file access to $this:
Code: Select all
<?php
$m = new MyClass();
$m->setMyVar(42);
$m->dump();
// $this->myVar = 42
Re: use of $this outside of class definition
Posted: Tue Mar 31, 2009 2:00 am
by Benjamin
Just to be clear, $this references the class that it's inside of. You cannot use $this outside of any class, period.