在PHP5中,使用self和$this有什么区别?

什么时候合适?


当前回答

从这篇博客文章:

self指当前类self可用于调用静态函数和引用静态成员变量self可以在静态函数中使用self还可以通过绕过vtable来关闭多态行为$这是指当前对象$this可用于调用静态函数$this不应用于调用静态成员变量。改用self。$this不能在静态函数中使用

其他回答

$this指当前类对象,self指当前类(Not对象)。类是对象的蓝图。所以你定义了一个类,但是你构造了对象。

换句话说,对静态成员或方法使用self,而对非静态成员和方法使用this。

同样在子/父场景中,self/parent主要用于标识子和父类成员和方法。

根据静态关键字,没有任何$self。只有$this用于引用类(对象)的当前实例,self用于引用类的静态成员。对象实例和类之间的区别在这里发挥作用。

在类定义中,$this引用当前对象,而self引用当前类。

必须使用self引用类元素,并使用$this引用对象元素。

self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable  

这里有一个小的基准(第7.2.24节):

            Speed (in seconds)  Percentage
$this->     0.91760206222534    100
self::      1.0047659873962     109.49909865716
static::    0.98066782951355    106.87288857386

4000 000次运行的结果。结论:没关系。这是我使用的代码:

<?php

class Foo
{
  public function calling_this() { $this->called(); }
  public function calling_self() { self::called(); }
  public function calling_static() { static::called(); }
  public static function called() {}
}

$foo = new Foo();
$n = 4000000;
$times = [];

// warmup
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }

$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
$times["this"] = microtime(true)-$start;

$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
$times["self"] = microtime(true)-$start;

$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }
$times["static"] = microtime(true)-$start;

$min = min($times);
echo $times["this"] . "\t" . ($times["this"] / $min)*100 . "\n";
echo $times["self"] . "\t" . ($times["self"] / $min)*100 . "\n";
echo $times["static"] . "\t" . ($times["static"] / $min)*100 . "\n";

以下是$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();
?>