gpt4 book ai didi

php - __call 方法需要知道何时按引用或按值传递 var

转载 作者:搜寻专家 更新时间:2023-10-31 21:17:54 25 4
gpt4 key购买 nike

我有一个对象,它使用神奇的 __call 方法来调用不同对象的方法。

有时此方法将用于调用需要其一个或多个参数作为引用的方法。

从 php 5.3 开始,调用时按引用传递已被弃用,因此我不能依赖按引用传递参数。我需要预测参数是否需要通过引用或值传递!

我将尝试用代码来解释这一点。我有以下两个类:

  • 主要对象
  • Extension_Object

注意:两个类之间没有继承结构。

class Main_Object  {

public function __call($method, $arguments)
{
// check this method is in an extended class
// …

$ext = new Extension_Object();

// call method in extension object
return call_user_func_array(array($ext, $method), $arguments);
}
}

class Extension_Object {

// takes two arguments
public function foo($p1, $p2)
{
// ...
}

// takes two arguments, the first being a reference
public function bar(&$p1, $p2)
{
// ...
}
}

目前我找不到在不产生 PHP 错误或警告的情况下调用 bar() 的方法

$obj = new Main_Object();

// works as expected
$obj->foo($bacon, $cheese);

// MESSAGE call-time pass-by-reference has been deprecated
$obj->bar(&$bacon, $cheese);

// WARNING parameter 1 expected to be a reference
$obj->bar($bacon, $cheese);

最佳答案

你可以设置 allow_call_time_pass_reference = 1;但这远不是一个好的解决方案。似乎没有别的办法。反射(reflection)可能会产生一个答案,但我个人对这个特定问题的了解还不够,无法就此提出真正的建议......

Is it possible to pass parameters by reference using call_user_func_array()?

PHP: call_user_func_array: pass by reference issue

关于php - __call 方法需要知道何时按引用或按值传递 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4462335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com