问题

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

每个时间是什么时候?



解决方法

Short Answer

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.

Full Answer

以下是非静态和静态成员变量 $ 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();
?>

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




相关问题推荐