萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP new self() 與 $this 關鍵字區別詳解:靜態綁定與實例化實戰

核心概念:self vs $this

特性self$this
指向當前類(靜態綁定)當前實例對象(動態綁定)
作用域類級別對象級別
繼承行為始終指向定義類指向實際實例化的子類
靜態成員訪問self::$staticVar不可訪問靜態成員
實例化new self() 創建當前類實例已是實例,無需實例化

new self() 實戰用法

1. 類內部實例化自身(工廠模式/單例)

class Phpernote {
    public function __construct() {
        echo '一聚教程網!';
    }
    public static function getInstance() {
        new self(); // 實例化當前類
    }
}
Phpernote::getInstance(); // 輸出:一聚教程網!

2. 靜態計數器模式

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 共享於所有實例,每次實例化遞增。

進階:晚期靜態綁定 (Late Static Binding)

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:: 運行期綁定,指向實際調用類

常見應用場景

  1. 單例模式: static::$instance = new static(); 支援子類繼承
  2. 工廠方法: 基類定義 create() 返回 new static()
  3. ActiveRecord: static::find() 返回當前模型查詢器
  4. 靜態屬性訪問: self::$config 存取類級配置

總結

  • new self() 在類內部創建**當前類**實例,不受繼承影響
  • 訪問靜態成員必須用 self:: 或 static::
  • 繼承體系中需多態行為時,優先用 static:: (LSB)
  • $this 僅能在實例方法中使用,指向具體對象
copyright © 萬盛學電腦網 all rights reserved