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
use of $this outside of class definition
Moderator: General Moderators
Re: use of $this outside of class definition
Well, it's not possible. You can't access something that doesn't exist.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
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
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
thanks
dhiren
Re: use of $this outside of class definition
It's not working. Also, we really don't provide private support here. Feel free to post your code, using the approriate code tags.cdhiren wrote:somehow this piece of code is working. can i have your email so that i could provide the source details ...
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Re: use of $this outside of class definition
Is this inside a template by any chance? Any file that is included by a class has access to $this: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
MyClass.php
Code: Select all
<?php
class MyClass {
public $myVar;
public function setMyVar($value) {
$this->myVar = $value;
}
public function dump() {
include 'other-file.php';
}
}Code: Select all
<?php
printf("\$this->myVar = %s<br />\n", $this->myVar);
Code: Select all
<?php
$m = new MyClass();
$m->setMyVar(42);
$m->dump();
// $this->myVar = 42Re: use of $this outside of class definition
Just to be clear, $this references the class that it's inside of. You cannot use $this outside of any class, period.