note 113914 deleted from language.oop5.basic by cmb
| From: | cmb@php.net | Date: | Mon, 21 Nov 2016 18:14:14 +0000 |
| Subject: | note 113914 deleted from language.oop5.basic by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207268@lists.php.net to get a copy of this message | ||
Note Submitter: sklemnov at gmail dot com
----
Small subtlety to anyone just starting out: using $this is for referencing an instance of the
current class (there are exceptions to this, but on the basic level it is mostly true; please do not
downvote this, it's not meant to be a PhD dissertation).
For instance,
class TestClass{
private $variable = "Hello";
function ReturnVar(){
return $this->variable;
}
function SetVar($input){
$this->variable = $input;
}
}
$t = new TestClass();
echo $t->ReturnVar();
$t->SetVar("Test");
echo $t->ReturnVar();
This is a useless piece of code that illustrates $this in functions.
echo $t->ReturnVar();
outputs "Hello", and then:
$t->SetVar("Test");
sets the object $t's copy of $variable to "Test". Finally,
echo $t->ReturnVar();
returns the new value of $t's copy of $variable, namely "Test".
using $this in the ReturnVar() function tells PHP that you want to return $t's copy of
$variable.
Suppose we took $this out of the above code:
class TestClass{
private $variable = "Hello";
function ReturnVar(){
return $variable;
}
function SetVar($input){
$variable= $input;
}
}
$t = new TestClass();
echo $t->ReturnVar();
$t->SetVar("Test");
echo $t->ReturnVar();
Would show nothing at all! PHP would not know that you meant to reference object $t's version
of $variable.