php 引用 问题
高洛峰
高洛峰 2017-04-10 14:24:47
[PHP讨论组]

function test() {
$a = 1;
$b = 2;
testa( 'testb', $a );
echo $a, $b;
}

function testa() {
$p = func_get_args();
$fun = $p[ 0 ];
$p1 = & $p[ 1 ]; // 如何将 $p[ 1 ] 用传址方式 传给 $p[ 0 ]
$fun( $p1 );
}

function testb( &$a, &$b ) {
$a = 'a';
$b = 'b';
}

test();

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
ringa_lee

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

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

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

<?php
function 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();

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

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号