【发布时间】:2019-06-05 20:14:43
【问题描述】:
我正在尝试理解为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 trait 的类。
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() 方法添加到我的设计中”
【问题讨论】:
-
看起来您没有在 foreach 循环中调用 bindArg。所以 $_arg 没有被设置。
-
bindArg应该只通过引用存储变量,因此只需要进行一次调用。随着$row的值变化,peekabo()应该输出$row变化后的值,因为$this->_arg应该保持相同的zval @RyDog -
\PDOStatement::bindParam是我想要实现的目标的完美示例。因为PDOStatement::execute保存值的zval(因此为什么可以在变量设置之前调用bindParam())只要它是在调用execute()之前设置的。我希望这更有意义@RyDog
标签: php oop reference pass-by-reference traits