PHP

php __set能用于多维数组吗

小樊
81
2024-11-29 20:21:58
栏目: 编程语言

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

0
看了该问题的人还看了