PHP变量是按值传递还是按引用传递?
当前回答
两种方法都可以。
在前面放一个“&”符号,你传递的变量就变成了它的原点,也就是说,你可以通过引用传递,而不是复制它。
so
$fred = 5;
$larry = & $fred;
$larry = 8;
echo $fred;//this will output 8, as larry and fred are now the same reference.
其他回答
根据PHP文档,它是按值计算的。
默认情况下,函数实参是按值传递的(这样,如果函数内实参的值改变了,它不会在函数外被改变)。为了允许函数修改其参数,它们必须通过引用传递。 要让函数的实参始终通过引用传递,请在函数定义中的实参名称前加上&。
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
关于如何将对象传递给函数,你仍然需要理解,没有“&”,你传递给函数的是一个对象句柄,对象句柄仍然是通过值传递的,它包含一个指针的值。但你不能改变这个指针,直到你通过引用传递它使用“&”
<?php
class Example
{
public $value;
}
function test1($x)
{
//let's say $x is 0x34313131
$x->value = 1; //will reflect outsite of this function
//php use pointer 0x34313131 and search for the
//address of 'value' and change it to 1
}
function test2($x)
{
//$x is 0x34313131
$x = new Example;
//now $x is 0x88888888
//this will NOT reflect outside of this function
//you need to rewrite it as "test2(&$x)"
$x->value = 1000; //this is 1000 JUST inside this function
}
$example = new Example;
$example->value = 0;
test1($example); // $example->value changed to 1
test2($example); // $example did NOT changed to a new object
// $example->value is still 1
?>
class Holder
{
private $value;
public function __construct( $value )
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function setValue( $value )
{
return $this->value = $value;
}
}
class Swap
{
public function SwapObjects( Holder $x, Holder $y )
{
$tmp = $x;
$x = $y;
$y = $tmp;
}
public function SwapValues( Holder $x, Holder $y )
{
$tmp = $x->getValue();
$x->setValue($y->getValue());
$y->setValue($tmp);
}
}
$a1 = new Holder('a');
$b1 = new Holder('b');
$a2 = new Holder('a');
$b2 = new Holder('b');
Swap::SwapValues($a1, $b1);
Swap::SwapObjects($a2, $b2);
echo 'SwapValues: ' . $a2->getValue() . ", " . $b2->getValue() . "<br>";
echo 'SwapObjects: ' . $a1->getValue() . ", " . $b1->getValue() . "<br>";
属性在没有通过引用传递时仍然是可以修改的,所以要小心。
输出:
SwapObjects: b, a SwapValues: a, b
实际上这两种方法都是有效的,但这取决于你的需求。通过引用传递值通常会使脚本变慢。因此,考虑到执行时间,最好按值传递变量。此外,当按值传递变量时,代码流更加一致。
PHP引用是一个别名,允许两个不同的变量写入相同的值。
在PHP中,如果你有一个包含对象的变量,这个变量不包含对象本身。相反,它包含该对象的标识符。对象访问器将使用标识符查找实际对象。因此,当我们在函数中使用对象作为参数或将其赋值给另一个变量时,我们将复制指向对象本身的标识符。
https://hsalem.com/posts/you-think-you-know-php.html
class Type {}
$x = new Type();
$y = $x;
$y = "New value";
var_dump($x); // Will print the object.
var_dump($y); // Will print the "New value"
$z = &$x; // $z is a reference of $x
$z = "New value";
var_dump($x); // Will print "New value"
var_dump($z); // Will print "New value"
推荐文章
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- 如何要求一个分叉与作曲家?
- 如何在php中创建可选参数?
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 如何从一个查询插入多行使用雄辩/流利
- 在PHP单元测试执行期间,如何在CLI中输出?