什么时候使用self over $ this? [英] When to use self over $this?
问题描述
在PHP 5中,使用 self
和 $ this
之间有什么区别?
In PHP 5, what is the difference between using self
and $this
?
每个适当的时间?
推荐答案
短回答
Short Answer
使用
$ this
来引用当前的
对象。使用self
引用
当前类。换句话说,对非静态成员使用
$ this-> member
,
使用self :: $ member
Use
$this
to refer to the current object. Useself
to refer to the current class. In other words, use$this->member
for non-static members, useself::$member
for static members.
完整答案
以下是正确对非静态使用 $ this
和 self
的示例和静态成员变量:
Full Answer
Here is an example of correct usage of $this
and self
for non-static and 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();
?>
以下是不正确使用 $ this
和 self
用于非静态和静态成员变量:
Here is an example of incorrect usage of $this
and self
for non-static and 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 is an example of polymorphism with $this
for 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();
?>
以下是抑制多态行为的示例,使用 self
的成员函数:
Here is an example of suppressing polymorphic behaviour by using self
for 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();
?>
想法是
$ this-> ; foo()
调用foo()
成员函数,无论什么>是当前对象的确切类型。如果对象是类型X
,则因此>调用X :: foo()
。如果对象是键入Y
,它调用Y :: foo()
。但是通过> self :: foo(),总是调用X :: foo()
。
The idea is that
$this->foo()
calls thefoo()
member function of whatever >is the exact type of the current object. If the object is oftype X
, it thus >callsX::foo()
. If the object is oftype Y
, it callsY::foo()
. But with >self::foo(),X::foo()
is always called.
b $ b
从 http://www.phpbuilder.com/board /showthread.php?t=10354489 :
由 http://board.phpbuilder.com/member.php?145249-laserlight
这篇关于什么时候使用self over $ this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!