• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP对象赋值给变量的两种方式的区别,一般赋值和引用赋值?

php 搞代码 3年前 (2022-01-25) 26次浏览 已收录 0个评论
文章目录[隐藏]

class Person {
public $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}

$lh = new Person(‘刘慧’, 23);
$a = $lh;
$b =& $lh;
————————————————————————-
请问$a 和 $b的区别?可以从内存堆栈的角度的分析。

··

回复内容:

PHP里不需要加&引用符号。所有对象都是引用传递,除非显式调用clone $object泻药
==============*本文来@源gao@daima#com搞(%代@#码@网2

搞代gaodaima码

=
我忘了是从哪个版本开始,PHP里不需要加&引用符号了。
加了会报一个语法错误,这个详细的解答呢,可以去问 @韩天峰 (他也回答了呢)。
亦或问问 @Laruence鸟叔这位大拿。
就酱基本类型的变量赋值,通常是真正的复制(理解为:2个指针,指向2块内存空间)。

<code class="language-php"><span class="x">$a = 100;</span><span class="x">$b = $a;</span><span class="x">unset($a);</span><span class="x">echo $b."\n";</span></code>

有一些区别,在你的例子中,如果你给b赋值一个新的值,lh的指向也会跟着改变,但是a不会有这个问题。

PHP手册中对引用的说法是:

Note:

$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

对PHP5中对象和引用的说法是:

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn’t contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

其实对对象变量取&更像是一个指向“指针”的指针。

@李怀志我也记得PHP里不需要加&引用符号,都是引用传递。但是经过我的测试(PHP5.6.7),我对以下内容存在疑惑:

<code class="language-php"><span class="x">class Person {</span><span class="x">  public $name = 'myName';</span><span class="x">}</span><span class="x">$obj = new Person;</span><span class="x">$assign = $obj;</span><span class="x">$reference = & $obj;</span><span class="x">$obj = null;//此操作很重要</span><span class="x">var_dump($obj);//得到null</span><span class="x">var_dump($assign);//得到object(Person)#1 (1) {["name"]=>string(6) "myName"}</span><span class="x">var_dump($reference);//得到null</span></code>

百度一下完全一样


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP对象赋值给变量的两种方式的区别,一般赋值和引用赋值?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址