[英]PHP returning by reference not working with normal functions but working with OOP
如果我嘗試此代碼:
<?php
class ref
{
public $reff = "original ";
public function &get_reff()
{
return $this->reff;
}
public function get_reff2()
{
return $this->reff;
}
}
$thereffc = new ref;
$aa =& $thereffc->get_reff();
echo $aa;
$aa = " the changed value ";
echo $thereffc->get_reff(); // says "the changed value "
echo $thereffc->reff; // same thing
?>
然后按引用返回,對象屬性$reff
的值隨着引用它的變量$aa
變化而改變。
但是,當我在不在類內的普通函數上嘗試此操作時,它將無法正常工作!
我嘗試了這段代碼:
<?php
function &foo()
{
$param = " the first <br>";
return $param;
}
$a = & foo();
$a = " the second <br>";
echo foo(); // just says "the first" !!!
它看起來像函數foo()
識別它通過引用返回,並且頑固地返回它想要的!
通過引用返回僅在OOP上下文中有效嗎?
這是因為當函數調用完成並且未設置對變量的函數本地引用時,函數的作用域就會崩潰。 隨后對該函數的任何調用都會創建一個新的$ param變量。
即使在函數中不是這種情況,您也會在每次調用函數時將變量重新分配給the first <br>
。
如果要證明按引用返回有效,請使用static關鍵字為函數變量賦予持久狀態。
看這個例子
function &test(){
static $param = "Hello\n";
return $param;
}
$a = &test();
echo $a;
$a = "Goodbye\n";
echo test();
回聲
Hello
Goodbye
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.