是的,__set
魔術方法在PHP中可以用于多維數組。當你嘗試為一個多維數組的元素賦值時,__set
方法會被觸發。這里有一個例子來說明如何使用__set
處理多維數組:
class MyArray {
private $array;
public function __construct() {
$this->array = array();
}
public function __set($name, $value) {
$keys = explode('->', $name);
$target = &$this->array;
foreach ($keys as $key) {
if (!isset($target[$key])) {
$target[$key] = array();
}
$target = &$target[$key];
}
$target = $value;
}
public function __get($name) {
$keys = explode('->', $name);
$target = $this->array;
foreach ($keys as $key) {
if (!isset($target[$key])) {
return null;
}
$target = $target[$key];
}
return $target;
}
}
$myArray = new MyArray();
$myArray->user->name = 'John Doe';
$myArray->user->age = 30;
$myArray->user->address->city = 'New York';
echo $myArray->user->name; // 輸出: John Doe
echo $myArray->user->age; // 輸出: 30
echo $myArray->user->address->city; // 輸出: New York
在這個例子中,我們創建了一個名為MyArray
的類,它使用__set
方法來處理多維數組的賦值。當我們嘗試為$myArray->user->name
、$myArray->user->age
和$myArray->user->address->city
賦值時,__set
方法會將值存儲在相應的多維數組中。