| 特性 | self | $this |
|---|---|---|
| 指向 | 當前類(靜態綁定) | 當前實例對象(動態綁定) |
| 作用域 | 類級別 | 對象級別 |
| 繼承行為 | 始終指向定義類 | 指向實際實例化的子類 |
| 靜態成員訪問 | self::$staticVar | 不可訪問靜態成員 |
| 實例化 | new self() 創建當前類實例 | 已是實例,無需實例化 |
class Phpernote {
public function __construct() {
echo '一聚教程網!';
}
public static function getInstance() {
new self(); // 實例化當前類
}
}
Phpernote::getInstance(); // 輸出:一聚教程網!
class TestSelf {
private static $first_count = 0;
private $last_count;
public function __construct() {
$this->last_count = ++self::$first_count; // 訪問靜態屬性
}
public function printSelf() {
print($this->last_count);
}
}
$abc = new TestSelf();
$abc->printSelf(); // 1
self::$first_count 共享於所有實例,每次實例化遞增。
PHP 5.3 引入 static:: 解決繼承場景問題:
class ParentClass {
public static function who() { echo __CLASS__; }
public static function testSelf() { self::who(); } // 輸出 ParentClass
public static function testStatic() { static::who(); } // 輸出 ChildClass
}
class ChildClass extends ParentClass {
public static function who() { echo __CLASS__; }
}
ChildClass::testSelf(); // ParentClass
ChildClass::testStatic(); // ChildClass
self:: 編譯期綁定,指向書寫所在類static:: 運行期綁定,指向實際調用類static::$instance = new static(); 支援子類繼承create() 返回 new static()static::find() 返回當前模型查詢器self::$config 存取類級配置new self() 在類內部創建**當前類**實例,不受繼承影響self:: 或 static::static:: (LSB)$this 僅能在實例方法中使用,指向具體對象