【问题标题】:Is there a way to use a 'pass by reference' in a class constructor?有没有办法在类构造函数中使用“通过引用传递”?
【发布时间】:2013-10-10 15:31:42
【问题描述】:

我有一个包含多个公共函数的类,它们都与相同的$_SESSION 索引/变量交互。我不想在每次调用它们时将该变量传递给每个函数,而是将它简单地传递给类构造函数并让函数从$this-> 中获取它。

我正在尝试做的示例:

$_SESSION['test'] = array('foo', 'bar');

class MyClass {
    // Pass by reference in ___construct arguments
    public function __construct(&$test_var) {
        $this->test_var = $test_var;
    }
    public function unset_foo() {
        unset($this->test_var[0]);
    }
}

$bar = new MyClass($_SESSION['test']);
$bar->unset_foo();

print_r($_SESSION['test']);

结果应该是:

Array
(
    [1] => 'bar'
)

但这不起作用。

有没有办法做到这一点?

【问题讨论】:

    标签: php pass-by-reference


    【解决方案1】:

    你总是要经过 ref:

    在这一行中,您不是通过引用分配,而是复制值:

        $this->test_var = $test_var;
    

    只需在此处添加一个&,以便$this->test_var 仍然拥有对$_SESSION['test'] 的引用:

        $this->test_var = &$test_var;
    

    【讨论】:

    • 完美,做到了。谢谢您的帮助。当它允许我时会将其设置为答案。
    猜你喜欢
    • 2011-07-28
    • 2013-11-17
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多