php 引用 問題

來源:互聯網
上載者:User
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() 來擷取一個參數變數的引用 ... 很遺憾 ... 你做不到 ...

不過我們可以用一些替代方案來完成 ... 沒細去琢磨 ... 第一時間能想到的方法類似下面這樣 ...

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

不太喜歡你的代碼風格所以小修改了一下 ... 但願不會影響恩 ...

這種方式雖然可以實現 ... 但是從架構的角度講不是太好 ...

因為在對象傳遞的過程中 ... 你無法取消這個引用 ... 所以盡量還是換一種程式結構吧 ...

恩 ... 就是這樣啦 ... 希望我沒誤會你的意思 ...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.