【问题标题】:Sharing array inside object through classes in php通过php中的类共享对象内部的数组
【发布时间】:2013-11-26 17:50:17
【问题描述】:

我的问题是我有一个通过两个类共享的对象,其中包含一个数组,其中包含一个数组,并且沿着脚本,有人会请求一些类的值,一个 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.

【问题讨论】:

    标签: php arrays pass-by-reference


    【解决方案1】:

    主要问题是你在 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);
    

    【讨论】:

    • 我的问题是我实际上在返回之前过滤了数组,这就是我“构建一个新数组”的原因。我希望这个新数组指向原始值。
    • 数组对象是你的选择,你可以清空它并再次填充它。
    • 我可能对这个问题不公平,因为我的值被过滤了,它们不是原始的,它实际上是对象。在改变自身的对象类中构建一个新函数就可以了。但是谢谢,您向我展示了问题在于创建新数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多