PHP中self與static區別和聯繫

參考:http://www.phpmianshi.com/?id=82

 

PHP官方也說過,大概意思是說self調用的就是本身代碼片段這個類,static - PHP 5.3加進來的只得是當前這個類,有點像$this的意思,static調用的是從堆內存中提取出來,訪問的是當前實例化的那個類,那麼 static 代表的就是那個類,例子比較容易明白些。

其實static就是調用的當前調用的類,比較抽象吧。

 

self refers to the same class whose method the new operation takes place in.

static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.

In the following example, B inherits both methods from A. self is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see  get_called_class() )

<?php

class Boo {

protected static $str = "This is class Boo";

/*

public static function get_info(){

echo get_called_class()."<br>"; //output Foo

echo self::$str; //output This is class Boo

}

*/

public static function get_info(){

echo get_called_class()."<br>"; //output Foo

echo static::$str; //output This is class Foo

}

}

class Foo extends Boo{

protected static $str = "This is class Foo";

}

Foo::get_info();

?>

 

再舉個例子:

class A {

  public static function get_self() {

    return new self();

  }



  public static function get_static() {

    return new static();

  }

}



class B extends A {}



echo get_class(B::get_self()); // A

echo get_class(B::get_static()); // B

echo get_class(A::get_static()); // A

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章