为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 $p[ 1 ] 用传址方式 传给 $p[ 0 ]

如何将 $p[ 1 ] 用传址方式 传给 $p[ 0 ]

PHP
蝴蝶不菲 2023-04-25 14:10:55
function test() {$a = 1;$b = 2;testa( 'testb', $a );echo $a, $b;}function testa() {$p = func_get_args();$fun = $p[ 0 ];$p1 = & $p[ 1 ]; $fun( $p1 );}function testb( &$a, &$b ) {$a = 'a';$b = 'b';}test();
查看完整描述

1 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

我依然不是太明白你的表达 ...

如果你是想通过 func_get_args() 来获取一个参数变量的引用 ... 很遗憾 ... 你做不到 ...

不过我们可以用一些替代方案来完成 ... 没细去琢磨 ... 第一时间能想到的方法类似下面这样 ...

<?phpfunction test() {    /* make an object and forget about reference ... */
    $sunyanzi = (object)[ 'a' => 1, 'b' => 2 ];    /* just call the function ... */
    func_caller( 'callee', $sunyanzi );    /* is this the result you want ..? */
    echo $sunyanzi->a, $sunyanzi->b;    /* done ... */
    return;

}function func_caller() {    /* you can not get reference via func_get_args() ... */
    $args = func_get_args();    /* using the most normal way to call the function ... */
    return $args[0]( $args[1] );

}function callee( $object ) {    /* a different way to assign value ... */
    $object->a = 'a';    $object->b = 'b';    /* actually i just replace "$" into "$object->" ... */
    return;

}/* here we go ... */test();

不太喜欢你的代码风格所以小修改了一下 ... 但愿不会影响恩 ...

这种方式虽然可以实现 ... 但是从架构的角度讲不是太好 ...

因为在对象传递的过程中 ... 你无法取消这个引用 ... 所以尽量还是换一种程序结构吧 ...

恩 ... 就是这样啦 ... 希望我没误会你的意思 ...


查看完整回答
反对 回复 2023-04-28
  • 1 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信