php - When to use self over $this? -
in php 5, difference between using self
, $this
?
when each appropriate?
short answer
use
$this
refer current object. useself
refer current class. in other words, use$this->member
non-static members, useself::$member
static members.
full answer
here example of correct usage of $this
, self
non-static , static member variables:
<?php class x { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo $this->non_static_member . ' ' . self::$static_member; } } new x(); ?>
here example of incorrect usage of $this
, self
non-static , static member variables:
<?php class x { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo self::$non_static_member . ' ' . $this->static_member; } } new x(); ?>
here example of polymorphism $this
member functions:
<?php class x { function foo() { echo 'x::foo()'; } function bar() { $this->foo(); } } class y extends x { function foo() { echo 'y::foo()'; } } $x = new y(); $x->bar(); ?>
here example of suppressing polymorphic behaviour using self
member functions:
<?php class x { function foo() { echo 'x::foo()'; } function bar() { self::foo(); } } class y extends x { function foo() { echo 'y::foo()'; } } $x = new y(); $x->bar(); ?>
the idea
$this->foo()
callsfoo()
member function of whatever >is exact type of current object. if object oftype x
, >callsx::foo()
. if object oftype y
, callsy::foo()
. >self::foo(),x::foo()
called.
from http://www.phpbuilder.com/board/showthread.php?t=10354489:
Comments
Post a Comment