我想通过引用传递对象,但它没有给出正确的结果这是我已经试过了
<?php
class my_class
{
var $my_var;
function my_class ($var)
{
global $obj_instance;
$obj_instance = &$this;
$this->my_var = $var;
}
}
$obj = new my_class ("something");
echo $obj->my_var."'n";
echo $obj_instance->my_var;
?>
输出:
预期结果:某物
在PHP手册的"What References Do"页面中,您可以阅读:
如果将引用分配给在函数中,引用将仅在函数内部可见。你可以通过使用$GLOBALS数组来避免这种情况。
示例:
<?php
$var1 = "Example variable";
$var2 = "";
function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =& $var1; // visible only inside the function
} else {
$GLOBALS["var2"] =& $var1; // visible also in global context
}
}
global_references(false);
echo "var2 is set to '$var2''n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2''n"; // var2 is set to 'Example variable'
?>
来自PHP.net