PHP:在类中通过引用传递数组,并在其他方法中使用它

时间:2018-06-21 09:00:04

标签: php arrays oop reference

我有以下代码段:

public function __construct($s, $e, &$v, &$rv, $needle, $parser, $id) {

        $this->start = $s;
        $this->end = $e;

        $this->vett = $v;
        $this->resVett = &$rv;

        $this->id = $id;

        $this->needle = $needle;

        $this->parser = $parser;
    }

    public function pushResult($result) {

        $this->resVett[] = $result;
    }

当我调用pushResult时,该值已正确插入,但原始数组(由rv引用的数组)不受影响。 您知道可能是什么问题吗?

1 个答案:

答案 0 :(得分:-1)

问题可能出在其他地方。我通过一个简单的示例检查了您的代码

<?php
class Example {

     public $value = [];
     public $reference = [];

     public function __construct($value, &$reference) {
        $this->value = $value;
        $this->reference =& $reference;
     }

     public function pushResult($result) {
        $this->reference[] = $result;
        $this->value[] = $result;
    }
}

$value = ['test'];
$reference = ['test'];

$example = new Example($value, $reference);
$example->pushResult('result');

echo 'Is Value variable same?';
var_dump($value === $example->value);

echo 'Is Reference variable same?';
var_dump($reference === $example->reference);

并像您一样传递引用应该可以