如何通过在 PHP 中通过引用传递变量来存储变量?

How can I store a variable by passing it by reference in PHP?

我正在努力掌握 PHP 7+ 为 Conflict Resolution. I also want to make a dynamic call to save() in my design, which will take in a argument by reference 引入的 OOP 概念。

为了在我将此添加添加到我的框架之前测试这个概念,我想尝试简单地输出变量的 zval 的基础知识。

我目前的特质是这样的:

trait Singleton {
    # Holds Parent Instance
    private static  $_instance;
    # Holds Current zval
    private         $_arg;

    # No Direct Need For This Other Than Stopping Call To new Class
    private function __construct() {}

    # Singleton Design
    public static function getInstance() {
        return self::$_instance ?? (self::$_instance = new self());
    }

    # Store a reference of the variable to share the zval
    # If I set $row before I execute this method, and echo $arg
    # It holds the correct value, _arg is not saving this same value?
    public function bindArg(&$arg) { $this->_arg = $arg; }

    # Output the value of the stored reference if exists
    public function helloWorld() { echo $this->_arg ?? 'Did not exist.'; }
}

然后我创建了一个 class,它利用了 Singleton 特性。

final class Test {
    use \Singleton { helloWorld as public peekabo; }
}

我像这样传入了我想引用的变量,因为该方法需要变量的引用——它还不需要设置。

Test::getInstance()->bindArg($row);

我现在想模仿从数据库结果中循环遍历行的概念,这个概念是允许将 save() 方法添加到我的设计中,但首先要让基本概念起作用。

foreach(['Hello', ',', ' World'] as $row)
    Test::getInstance()->peekabo();

问题是,输出如下所示:

Did not exist.Did not exist.Did not exist.

我的预期输出如下:

Hello, World

如何将 zval 存储在我的 class 中以便以后在单独的方法中使用?


Demo for future viewers of this now working thanks to the answers

Demo of this working for a database concept like I explained in the question 这里:

"I now want to mimic the concept of looping through rows from a database result, the concept is to allow a save() method to be added to my design"

使用 public function bindArg(&$arg) { $this->_arg = &$arg; } 它适用于 PHP 7.3