note 113914 added to language.oop5.basic

From: Date: Tue, 17 Dec 2013 00:44:52 +0000
Subject: note 113914 added to language.oop5.basic
Groups: php.notes 
Request: Send a blank email to php-notes+get-197956@lists.php.net to get a copy of this message
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. ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/language.oop5.basic.php Edit -- https://master.php.net/note/edit/113914 Del: integrated -- https://master.php.net/note/delete/113914/integrated Del: useless -- https://master.php.net/note/delete/113914/useless Del: bad code -- https://master.php.net/note/delete/113914/bad+code Del: spam -- https://master.php.net/note/delete/113914/spam Del: non-english -- https://master.php.net/note/delete/113914/non-english Del: in docs -- https://master.php.net/note/delete/113914/in+docs Del: other reasons-- https://master.php.net/note/delete/113914 Reject -- https://master.php.net/note/reject/113914 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#197956) next »