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
#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