我什么时候应该在 '$this' 上使用 'self'? [英] When should I use 'self' over '$this'?
问题描述
在 PHP 5 中,使用 self
和 $this
有什么区别?
什么时候合适?
简答
<块引用>使用 $this
来引用当前目的.使用 self
来引用当前班级.换句话说,使用$this->member
用于非静态成员,将 self::$member
用于静态成员.
完整答案
以下是$this
和self
用于非静态和静态成员变量的正确用法示例:
non_static_member .' '.self::$static_member;}}新的 X();?>
这里是一个不正确使用$this
和self
用于非静态和静态成员变量的例子:
static_member;}}新的 X();?>
这里是一个多态的例子,$this
用于成员函数:
foo();}}Y 类扩展 X {函数 foo() {echo 'Y::foo()';}}$x = 新 Y();$x->bar();?>
以下是一个通过对成员函数使用 self
来抑制多态行为的示例:
bar();?>
<块引用>
这个想法是 $this->foo()
调用 foo()
成员函数,无论当前对象的确切类型是什么.如果对象是type X
,它就会调用X::foo()
.如果对象是type Y
,它会调用Y::foo()
.但是对于 self::foo(),X::foo()
总是被调用.
来自 http://www.phpbuilder.com/board/showthread.php?t=10354489:
由 http://board.phpbuilder.com/member.php?145249-laserlight
In PHP 5, what is the difference between using self
and $this
?
When is each appropriate?
Short Answer
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.
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();
?>
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();
?>
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();
?>
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.
From http://www.phpbuilder.com/board/showthread.php?t=10354489:
By http://board.phpbuilder.com/member.php?145249-laserlight
这篇关于我什么时候应该在 '$this' 上使用 'self'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!