为什么对象会自动从另一个对象中继承值?

[英]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