php - 我什么时候应该使用 'self' 而不是 '$this' ?

标签 php class oop scope

在 PHP 5 中,使用 self$this 有什么区别?

什么时候合适?

最佳答案

简答

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

完整答案

下面是$thisself对非静态和静态成员变量的正确用法示例:

<?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();
?>

下面是 $thisself 对非静态和静态成员变量的不正确用法示例:

<?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();
?>

下面是 polymorphism 的示例,其中 $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();
?>

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

来自 http://www.phpbuilder.com/board/showthread.php?t=10354489 :

作者 http://board.phpbuilder.com/member.php?145249-laserlight

关于php - 我什么时候应该使用 'self' 而不是 '$this' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/151969/

相关文章:

php - 使用ajax获取json以显示给用户

javascript - 如何在构造函数中将对象添加到数组

php - CSS、JS包含方法

php - 如何修改 SQL 来加快速度?

None 类型或 dict 的类成员的 Python 类型提示

c++ "Incomplete type not allowed"访问类引用信息时出错(带有前向声明的循环依赖)

Wordpress 中表格的 CSS

C++:为什么访问类数据成员比访问全局变量慢?

c++ - 如何防止通过指向其父类型的指针删除对象?

php - 如何使用 echo 调试 Behat 3 中的功能