通过php中的类在对象内共享数组

时间:2013-11-26 17:50:18

标签: php arrays pass-by-reference

我的问题是我有一个通过两个类共享的对象,其中包含一个数组,并且在脚本中,有人将请求某些类的值,foreach循环将更改此值,我希望此更改为影响价值的每一个参考。

class bar {

    protected $obj;

    function __construct(&$obj) {
        $this->obj = $obj;
    }

    public function output() {
        print_r($this->obj->value);
    }

}

class foo {

    protected $obj;

    function __construct(&$obj) {
        $this->obj = $obj;
    }

    public function val() {
        $result = array();
        foreach($this->obj->value as $it){
            $result[] = $it;
        }
        return $result;
    }

}
// Shared Object
$obj = new stdClass();
// Default value
$obj->value = array('teste', 'banana', 'maca');
// Class 1
$bar = new bar($obj);
// Class 2
$foo = new foo($obj);

// Someone requests from class 2 the values and changes it
$new = $foo->val();
$new[] = 'abc';

// Class 1 outputs the value
$bar->output(); // this will print the default value. I want this to also have 'abc' value.

1 个答案:

答案 0 :(得分:2)

主要问题是你要在foo:val上构建一个新数组,你必须返回要修改的原始对象。

我建议使用ArrayObject,具有相同的数组行为但是是一个对象,然后总是通过引用传递。

<?php

class MyArrayObject extends ArrayObject {
    public function replace(Array $array)
    {
        foreach($this->getArrayCopy() as $key => $value) {
            $this->offsetUnset($key);
        }

        foreach ($array as $key => $value) {
            $this[$key] = $value;
        }
    }


}

class bar {

    protected $obj;

    function __construct(MyArrayObject $obj) {
        $this->obj = $obj;
    }

    public function output() {
        print_r($this->obj);
    }

}

class foo {

    protected $obj;

    function __construct(MyArrayObject $obj) {
        $this->obj = $obj;
    }

    public function val() {
        $result = array('foo', 'bar');
        $this->obj->replace($result);

        return $this->obj;
    }

}
// Shared Object
$obj = new MyArrayObject(array('teste', 'banana', 'maca'));
// Class 1
$bar = new bar($obj);
// Class 2
$foo = new foo($obj);

// Someone requests from class 2 the values and changes it
$new = $foo->val();
$new[] = 'abc';

// Class 1 outputs the value
$bar->output(); // this will print the default value. I want this to also 

var_dump($obj);