Home > Backend Development > PHP Tutorial > php 引用 问题

php 引用 问题

WBOY
Release: 2016-06-06 20:50:45
Original
1014 people have browsed it

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();

回复内容:

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();

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

如果你是想通过 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();
Copy after login

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

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

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

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

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template