PHP對象賦值給變數的兩種方式的區別,一般賦值和引用賦值?

來源:互聯網
上載者:User
關鍵字 name age public Person this
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瀉藥
===============
我忘了是從哪個版本開始,PHP裡不需要加&引用符號了。
加了會報一個語法錯誤,這個詳細的解答呢,可以去問 @韓天峰 (他也回答了呢)。
亦或問問 @Laruence鳥叔這位大拿。
就醬基本類型的變數賦值,通常是真正的複製(理解為:2個指標,指向2塊記憶體空間)。
$a = 100;$b = $a;unset($a);echo $b."\n";
有一些區別,在你的例子中,如果你給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),我對以下內容存在疑惑:
class Person {  public $name = 'myName';}$obj = new Person;$assign = $obj;$reference = & $obj;$obj = null;//此操作很重要var_dump($obj);//得到nullvar_dump($assign);//得到object(Person)#1 (1) {["name"]=>string(6) "myName"}var_dump($reference);//得到null
百度一下完全一樣
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.