是的,__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
方法会将值存储在相应的多维数组中。