在 PHP 中,魔法函數為物件提供了額外的行為,增強了程式碼的易讀性和可維護性。這些函數在物件建立、存取、比較和銷毀時自動呼叫。常見的魔法函數包括:__construct():建立新物件時用於初始化屬性。 __destruct():銷毀物件時用於清理資源。 __get() 和 __set():存取或設定不存在的屬性時呼叫。 __call():呼叫不存在的方法時呼叫。 __toString():強制物件轉換為字串時呼叫。

PHP 魔法函數揭秘
在PHP 中,魔法函數賦予了物件特殊的行為,增強了程式碼的可讀性和可維護性。它們在物件建立、存取、比較和銷毀時自動呼叫。
常見魔法函數
-
__construct():當建立新物件時調用,用於初始化屬性。
-
__destruct():當物件被銷毀時調用,用於清理資源。
-
__get() 和 __set():在存取或設定不存在的屬性時呼叫。
-
__call():在呼叫不存在的方法時呼叫。
-
__toString():在物件被強制轉換為字串時呼叫。
實戰案例
使用__construct() 初始化物件
1 2 3 4 5 6 7 8 9 10 11 12 | class Person {
public $name ;
public $age ;
public function __construct( $name , $age ) {
$this ->name = $name ;
$this ->age = $age ;
}
}
$person = new Person( 'John Doe' , 30);
echo $person ->name;
|
登入後複製
使用__destruct( ) 清理資源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Database {
private $connection ;
public function __construct() {
$this ->connection = new MongoClient();
}
public function __destruct() {
$this ->connection->close();
}
}
$db = new Database();
|
登入後複製
使用__get() 和__set() 存取和設定動態屬性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class MyClass {
private $data = [];
public function __get( $name ) {
return $this ->data[ $name ] ?? null;
}
public function __set( $name , $value ) {
$this ->data[ $name ] = $value ;
}
}
$obj = new MyClass();
$obj ->test = 'foo' ;
echo $obj ->test;
|
登入後複製
以上是PHP魔法函數揭秘的詳細內容。更多資訊請關注PHP中文網其他相關文章!