通过引用将参数可移植地传递给 PHP 的 ReflectionMethod::invokeArgs

发布于 2024-08-14 05:22:16 字数 971 浏览 5 评论 0原文

似乎有点用词不当,因为在 PHP 5.3 中不推荐使用引用传递...无论如何,我想做的是使用反射编写一个单元测试框架,它允许您将参数传递给需要引用的方法。例如

class Bar {
    function TestMethod($arg1, &$result) {
        $result = 'hello';
        return true;
    }
}

$rc = new ReflectionMethod('Bar', 'TestMethod');
$return_val = $rc->invokeArgs($instance, $arguments);

现在,我在 http://www.phwinfo.com/forum/comp-lang-php/273316-how-invoke-reflectionmethod-pass-variable-reference-asargument.html 这让我明白只需将变量引用粘贴到我的 $arguments 数组中:

$arguments = array('arg1', &$byref_result);

这确实有效,但会给出“已弃用:调用时传递引用已被弃用”错误。我想确保这段代码是向前兼容的,所以如果他们在 PHP 6 中完全删除它,我就不会被搞砸了。显然,由于我的测试框架存在缺陷,我不想重写项目中的任何代码。有什么想法或建议吗?谢谢! :)

PS 我尝试查看 phpunit 的文档,看看它是否可以做到这一点,但该网站目前似乎已关闭。任何指向“不要重新发明轮子”解决方案的链接都非常受欢迎,尽管我也对这个问题本身感到好奇。

Seemingly something of a misnomer, as pass by reference is deprecated in PHP 5.3... anyway, what I'm trying to do is write a unit test framework using reflection, that allows you to pass arguments to a method which requires a reference. e.g.

class Bar {
    function TestMethod($arg1, &$result) {
        $result = 'hello';
        return true;
    }
}

$rc = new ReflectionMethod('Bar', 'TestMethod');
$return_val = $rc->invokeArgs($instance, $arguments);

Now, I found a forum post at http://www.phwinfo.com/forum/comp-lang-php/273316-how-invoke-reflectionmethod-pass-variable-reference-asargument.html which clued me into simply sticking a variable reference into my $arguments array:

$arguments = array('arg1', &$byref_result);

This does work but gives a 'Deprecated: Call-time pass-by-reference has been deprecated' error. I'd like to make sure this code is forwards compatible, so if they remove it completely in PHP 6 I won't be screwed. Obviously I'd prefer not to have to rewrite any code in my project because of shortfalls in my testing framework. Any ideas or suggestions? Thanks! :)

P.S. I tried to hit up phpunit's documentation to see if it can do it but the site seems to be down for the moment. Any links to "don't re-invent the wheel" solutions very welcome, though I'm also curious about the question itself.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开柳相依 2024-08-21 05:22:16

此代码没有问题

class Bar {
    function test($arg1, &$result) {
        $result = 'hello';
    }
}

$arguments = array('', &$b);
$rc = new ReflectionMethod('Bar', 'test');
$rc->invokeArgs(new Bar, $arguments);
var_dump($b);

打印“hello”,没有警告

您可以发布您的确切代码吗?

no problems with this code

class Bar {
    function test($arg1, &$result) {
        $result = 'hello';
    }
}

$arguments = array('', &$b);
$rc = new ReflectionMethod('Bar', 'test');
$rc->invokeArgs(new Bar, $arguments);
var_dump($b);

prints "hello", no warnings

can you post your exact code?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文