在PHP5中,使用self和$this有什么区别?
什么时候合适?
在PHP5中,使用self和$this有什么区别?
什么时候合适?
当前回答
$this指当前类对象,self指当前类(Not对象)。类是对象的蓝图。所以你定义了一个类,但是你构造了对象。
换句话说,对静态成员或方法使用self,而对非静态成员和方法使用this。
同样在子/父场景中,self/parent主要用于标识子和父类成员和方法。
其他回答
在类定义中,$this引用当前对象,而self引用当前类。
必须使用self引用类元素,并使用$this引用对象元素。
self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable
self(不是$self)指的是类的类型,而$this指的是该类的当前实例。self用于静态成员函数,允许您访问静态成员变量$这用于非静态成员函数,是对调用成员函数的类实例的引用。
因为这是一个对象,所以可以像这样使用它:$this->member
因为self不是一个对象,所以它基本上是一个自动引用当前类的类型。您可以像:self::member一样使用它
在PHP中,使用self关键字访问静态财产和方法。
问题是,无论method()是否声明为静态,都可以在任何地方用self::method(。那么你应该使用哪一种?
考虑以下代码:
class ParentClass {
function test() {
self::who(); // will output 'parent'
$this->who(); // will output 'child'
}
function who() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function who() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
在本例中,self::who()将始终输出“parent”,而$this->who(()将取决于对象的类。
现在我们可以看到self是指调用它的类,而$this是指当前对象的类。
因此,只有当$this不可用时,或者当您不想让后代类覆盖当前方法时,才应该使用self。
self::用于当前类的关键字,基本上用于访问静态成员、方法和常量。但是在$this的情况下,不能调用静态成员、方法和函数。
您可以在另一个类中使用self::关键字并访问静态成员、方法和常量。当它将从父类扩展时,在$this关键字的情况下也是如此。当另一个类将从父类扩展时,您可以访问该类中的非静态成员、方法和函数。
下面给出的代码是self::和$this关键字的示例。只需复制并粘贴代码文件中的代码,即可看到输出。
class cars{
var $doors = 4;
static $car_wheel = 4;
public function car_features(){
echo $this->doors . " Doors <br>";
echo self::$car_wheel . " Wheels <br>";
}
}
class spec extends cars{
function car_spec(){
print(self::$car_wheel . " Doors <br>");
print($this->doors . " Wheels <br>");
}
}
/********Parent class output*********/
$car = new cars;
print_r($car->car_features());
echo "------------------------<br>";
/********Extend class from another class output**********/
$car_spec_show = new spec;
print($car_spec_show->car_spec());
简短回答
使用$this表示当前对象使用self指代当前类别。换句话说,使用$this->非静态成员的成员,对静态成员使用self::$member。
完整答案
以下是非静态和静态成员变量$this和self的正确用法示例:
<?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的示例:
<?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();
?>
下面是一个成员函数使用$this的多态性示例:
<?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来抑制多态行为的示例:
<?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()。
从…起http://www.phpbuilder.com/board/showthread.php?t=10354489:
通过http://board.phpbuilder.com/member.php?145249-激光灯