PHP中的stdClass是一個通用的空對象,用于存儲和操縱屬性。它可以實現以下功能:
$obj = new stdClass();
$obj->name = "John";
$obj->age = 30;
$obj->city = "New York";
echo $obj->name; // 輸出 "John"
echo $obj['age']; // 輸出 30
foreach ($obj as $key => $value) {
echo $key . ": " . $value . "\n";
}
unset($obj->city);
$obj2 = new stdClass();
$obj2->job = "Engineer";
$obj->merge($obj2);
toArray()
方法將對象轉換為數組。例如:$array = $obj->toArray();
__get()
、__set()
、__call()
等)來自定義對象屬性的操作行為。例如:class CustomstdClass extends stdClass {
public function __get($name) {
return "Property '$name' not found";
}
public function __set($name, $value) {
$this->$name = $value;
}
}
這些功能使得stdClass成為PHP中一個非常靈活和實用的數據結構。