2
class Test {
    public function __construct() {
        self::runTest();
        Test::runTest();
    }

    public static function runTest() {
        echo "Test running";
    }
}

// echoes 2x "Test running"
new Test();

self::runTest()和有什么区别Test::runTest()吗?如果是这样,我应该使用哪一个?

self::runTest()在类内和类外调用方法Test::runTest()时?

4

3 回答 3

5

您应该self::runTest()从类方法内部和类方法Test::runTest()外部调用

于 2013-01-21T13:39:42.153 回答
4

self::runTest() 在类内调用方法,而在类外调用 Test::runTest()?

确切地!

于 2013-01-21T13:40:36.707 回答
4

这是一些示例代码来显示正在发生的事情:

class A {
  function __construct(){
     echo get_class($this),"\n"; 
     echo self::tellclass();
     echo A::tellclass();
  }

  static function tellclass(){
    echo __METHOD__,' ', __CLASS__,"\n";
  }

}

class B extends A {
}

class C extends A{
    function __construct(){
        echo "parent constructor:\n";
        parent::__construct();
        echo "self constructor:\n";
        echo get_class($this),"\n";
        echo self::tellclass();
        echo C::tellclass();
    }

    static function tellclass(){
        echo __METHOD__, ' ', __CLASS__,"\n";
    }
}

$a= new A;
// A
//A::tellclass A
//A::tellclass A

$b= new B;
//B
//A::tellclass A
//A::tellclass A

$c= new C;

//parent constructor:
//C    
//A::tellclass A
//A::tellclass A

//self constructor:
//C
//C::tellclass C
//C::tellclass C

要点是A::tellclass() 始终调用中tellclass定义的方法A。但是self::tellclass()允许子类使用他们自己的版本,tellclass() 如果他们有的话。正如@One Trick Pony 所说,您还应该查看后期静态绑定:http ://ca2.php.net/manual/en/language.oop5.late-static-bindings.php

于 2013-01-21T14:12:19.027 回答