English 中文(简体)
使用 ArrayObject 来存储阵列
原标题:Using ArrayObject to store arrays

我正试图存储一个阵列, 并使用扩展阵列Object 的定制类来操作阵列 。

class MyArrayObject extends ArrayObject {
    protected $data = array();

    public function offsetGet($name) {
        return $this->data[$name];
    }

    public function offsetSet($name, $value) {
        $this->data[$name] = $value;
    }

    public function offsetExists($name) {
        return isset($this->data[$name]);
    }

    public function offsetUnset($name) {
        unset($this->data[$name]);
    }
}

问题是如果我这样做:

$foo = new MyArrayObject();
$foo[ blah ] = array( name  =>  bob );
$foo[ blah ][ name ] =  fred ;
echo $foo[ blah ][ name ];

输出为bob 而不是 fred。 是否有办法可以让它工作而不改变上面的4行?

最佳回答

这是已知的 ArrayAccess (“ PHPP 通知: 间接修改 MyArrayObject 上载元素没有效果” ) 的行为 。

http://php.net/manual/en/class.arrayaccess.php" rel=“nofollow>http://php.net/manual/en/class.arrayccess.php

在 My ArrayObject 中执行此操作 :

public function offsetSet($offset, $data) {
    if (is_array($data)) $data = new self($data);
    if ($offset === null) {
        $this->data[] = $data;
    } else {
        $this->data[$offset] = $data;
    }
} 
问题回答

暂无回答




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签