為什么對象會自動從另一個對象中繼承值?

[英]Why do objects automatically inherit values from another object initiated before or after?


Here Student's class method and variable get affected and present in other object too i.e. $obj1, why does this happen?

這里,學生的類方法和變量也會在其他對象中受到影響,比如$obj1,為什么會發生這種情況?

class Student {
    public $name;
    public $age;
    public function callme() {
        return 'called';
    }
}

$obj = new Student();
$obj1 = $obj;
$obj->name = 'David';
$obj->age = 12;
echo '<pre>';
print_r($obj);
print_r($obj1);
echo $obj1->callme();

ouput :

輸出:

Student Object
(
    [name] => David
    [age] => 12
)
Student Object
(
    [name] => David
    [age] => 12
)
called

2 个解决方案

#1


3  

This behaviour is explained here, when you do the following:

這里解釋這種行為,當您執行以下操作時:

$obj = new Student();
$obj1 = $obj;

$obj1 is actually a reference to $obj so any modifications will be reflected on the original object. If you need a new object, then declare one using the new keyword again (as that's what it's for) as such:

$obj1實際上是對$obj的引用,因此任何修改都將反映在原始對象上。如果您需要一個新對象,那么使用new關鍵字再次聲明一個對象(這就是它的用途):

$obj = new Student();
$obj1 = new Student();

(Also, I see @Wizard posted roughly the same thing half way through me writing this but I'll leave this here for sake of examples)

(另外,我看到@Wizard在我寫這篇文章的過程中,發布了大致相同的內容,但為了便於示例,我將把它留在這里)

#2


1  

As of PHP 5, $obj and $obj1 hold a copy of the object identifier, which points to the same object. Read http://php.net/manual/en/language.oop5.references.php

對於PHP 5, $obj和$obj1持有指向相同對象的對象標識符的副本。閱讀http://php.net/manual/en/language.oop5.references.php


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/30/79076c5e5de6ed981c6b91f1fe1476d5.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com