通过php中的类共享对象内部的数组 [英] Sharing array inside object through classes in php

查看:51
本文介绍了通过php中的类共享对象内部的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我有一个对象,该对象通过两个类共享,该类内部包含一个数组,并且沿着脚本,有人会向某些类请求值,而foreach循环将更改该值,并且我希望此更改为影响值的每个引用。

My problem is that I have an object shared through two classes that contains an array inside of it and along the script, someone will request some of the classes the value and a foreach loop will change such value and I want this change to affect every reference of the value.

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.


推荐答案

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

The main problem, is that you are building a new array at foo:val, you must return the original object to be modified.

我建议使用 ArrayObject ,具有与array相同的行为,但它是一个对象,因此始终通过引用传递。

I suggest use ArrayObject, have the same behavior of array but is a object, then always is passed by reference.

<?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);

这篇关于通过php中的类共享对象内部的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆