PHP更改类之外的类变量

时间:2014-06-12 09:21:05

标签: php class object reference pass-by-reference

对于这个问题的措辞道歉,我难以解释我所追求的内容,但希望这是有道理的。

假设我有一个类,我希望通过其中一个方法传递变量,然后我有另一个输出此变量的方法。这一切都很好,但我所追求的是,​​如果我更新最初传递的变量,并在类方法之外执行此操作,它应该反映在类中。

我创建了一个非常基本的例子:

class Test {

    private $var = '';

    function setVar($input) {
        $this->var = $input;
    }

    function getVar() {
        echo 'Var = ' . $this->var . '<br />';
    }

}

如果我跑

$test = new Test();
$string = 'Howdy';
$test->setVar($string);
$test->getVar();

我得到了

Var = Howdy

然而,这是我想要的流程:

$test = new Test();
$test->setVar($string);

$string = 'Hello';

$test->getVar();

$string = 'Goodbye';

$test->getVar();

预期输出为

Var = Hello
Var = Goodbye

我不知道这个的正确命名是什么,我尝试使用对原始变量的引用,但没有运气。

我过去曾经遇到过这个问题,有PDO准备好的陈述,请参阅Example #2

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();

我知道我可以将变量更改为public并执行以下操作,但它与PDO类处理它的方式并不完全相同,我真的希望模仿这种行为。

$test = new Test();
$test->setVar($string);

$test->var = 'Hello';

$test->getVar();

$test->var = 'Goodbye';

$test->getVar();

非常感谢任何帮助,想法,指示或建议,谢谢。

3 个答案:

答案 0 :(得分:4)

也许使用 引用

class Test {

    private $var = '';

    function setVar(&$input) {
        $this->var = &$input;
    }

    function getVar() {
        echo 'Var = ' . $this->var . '<br />';
    }

}


$string = null;
$test = new Test();
$test->setVar($string);

$string = 'Hello';

$test->getVar();

$string = 'Goodbye';

$test->getVar();

答案 1 :(得分:3)

使setVar()函数传递参数by reference

function setVar(&$input) {
    $this->var = &$input; // Note the & before $input
}

Working demo

答案 2 :(得分:-1)

将$ var更改为public,您可以执行此操作

<?php

class Test {

    public $var;

    function getVar() {
        echo 'Var = ' . $this->var . '<br />';
    }

}

$test = new Test();
$test->var = 'Hey dude';
echo $test->var;

输出

Hey Dude