note 100314 added to language.oop5.basic
| From: | Doug at osu1 dot php dot net | Date: | Thu, 07 Oct 2010 14:29:10 +0000 |
| Subject: | note 100314 added to language.oop5.basic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173054@lists.php.net to get a copy of this message | ||
What is the difference between $this and self ?
Inside a class definition, $this refers to the current object, while self refers to the current
class.
It is necessary to refer to a class element using self ,
and refer to an object element using $this .
Note also how an object variable must be preceded by a keyword in its definition.
The following example illustrates a few cases:
<?php
class Classy {
const STAT = 'S' ; // no dollar sign for constants (they are always static)
static $stat = 'Static' ;
public $publ = 'Public' ;
private $priv = 'Private' ;
protected $prot = 'Protected' ;
function __construct( ){ }
public function showMe( ){
print '<br> self::STAT: ' . self::STAT ; // refer to a (static) constant like
this
print '<br> self::$stat: ' . self::$stat ; // static variable
print '<br>$this->stat: ' . $this->stat ; // legal, but not what you
might think: empty result
print '<br>$this->publ: ' . $this->publ ; // refer to an object variable
like this
print '<br>' ;
}
}
$me = new Classy( ) ;
$me->showMe( ) ;
/* Produces this output:
self::STAT: S
self::$stat: Static
$this->stat:
$this->publ: Public
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 74.94.131.53
----
Manual Page -- http://www.php.net/manual/en/language.oop5.basic.php
Edit -- https://master.php.net/note/edit/100314
Del: integrated -- https://master.php.net/note/delete/100314/integrated
Del: useless -- https://master.php.net/note/delete/100314/useless
Del: bad code -- https://master.php.net/note/delete/100314/bad+code
Del: spam -- https://master.php.net/note/delete/100314/spam
Del: non-english -- https://master.php.net/note/delete/100314/non-english
Del: in docs -- https://master.php.net/note/delete/100314/in+docs
Del: other reasons-- https://master.php.net/note/delete/100314
Reject -- https://master.php.net/note/reject/100314
Search -- https://master.php.net/manage/user-notes.php