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

标签 php oop reference pass-by-reference traits

我正在尝试掌握 PHP 7+ 中引入的 OOP 概念 Conflict Resolution 。我还想在我的设计中动态调用 save(),它将接受参数 by reference .

为了在框架中添加此功能之前测试这个概念,我想尝试一下简单输出变量 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.'; }
}

然后我创建了一个利用 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 存储在我的类中以便以后在单独的方法中使用?


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

关于php - 如何在 PHP 中通过引用传递变量来存储变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54137505/

相关文章:

php - 使用一条语句从多个表中删除多个mysql行

php - 将应用程序连接到本地mysql数据库

c++ - 通过引用分配 vector

javascript - 对象引用的变量重新分配使其他对象保持不变(无 “transitive” 分配)

php oo - 如何做对?

javascript - JS - 理解闭包

PHP循环遍历月份数组

PHP (Laravel 4) 和 PostgreSQL 搜索

python - 重写子类中的 __new__ 以创建特定的父类实例是一种反模式吗?

Swift:如何使具有子类返回类型的函数符合协议(protocol),其中父类(super class)被定义为返回类型?