我正在尝试掌握Conflict Resolution
在PHP 7+中引入的OOP概念。我还想在设计中动态调用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在这里:
“我现在想模仿从数据库结果中遍历行的概念,该概念是允许将save()方法添加到我的设计中”
答案 0 :(得分:3)
使用public function bindArg(&$arg) { $this->_arg = &$arg; }
与PHP 7.3一起使用