Reputation: 45
I have a class that extends of another one.
Class Test
class Test
{
private $id;
private $name;
private $age;
private $number;
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
return $this;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
return $this;
}
public function getNumber() {
return $this->number;
}
public function setNumber($number) {
$this->number = $number;
return $this;
}
}
Class TestCopy
use Test;
class TestCopy extends Text
{
}
And then I have an object of the class Test:
$object = new Test();
$object->setId = 1;
$object->setName = Tom;
$object->setAge = 20;
$object->setNumber = 10;
How I can create an object of the class TestCopy (that will have the same attributes), and clone all the values of the object $object?
I tried with clone:
$objectCopy = clone $object;
But the object $objectCopy have to instance the class TestCopy, and when I clone, it instance the class Test.
And I tried so too:
foreach (get_object_vars($object) as $key => $name) {
$objectCopy->$key = $name;
}
But the attributes are private and when I call the function get_object_vars it returns null. Any idea? Thank very much!
Upvotes: 3
Views: 1584
Reputation: 2945
try this, Once you instantiate a object, you can't change the class (or other implementation details)
You can simulate it like so:
<?php
class Test
{
private $id;
private $name;
private $age;
private $number;
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
return $this;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
return $this;
}
public function getNumber() {
return $this->number;
}
public function setNumber($number) {
$this->number = $number;
return $this;
}
public function toArray()
{
return get_object_vars($this);
}
}
class TestCopy extends Test
{
public $fakeAttribute;
}
function getTestCopy($object)
{
$copy = new TestCopy();
foreach($object->toArray() as $key => $value) {
if(method_exists($copy, 'set'.ucfirst($key))) {
$copy->{'set'.ucfirst($key)}($value);
}
}
return $copy;
}
$object = new Test();
$object->setId(1);
$object->setName('Tom');
$object->setAge(20);
$object->setNumber(10);
$copy = getTestCopy($object);
$copy->fakeAttribute = 'fake value';
echo "<pre>";
print_r($object->toArray());
print_r($copy->toArray());
output :
Array
(
[id] => 1
[name] => Tom
[age] => 20
[number] => 10
)
Array
(
[fakeAttribute] => fake value
[id] => 1
[name] => Tom
[age] => 20
[number] => 10
)
Upvotes: 2