I have 2 classes that one of them extends another:
class a{
private $name;
public function __construct(){
}
public function get($v){
$this->name=$v;
}
}
class b extends a{
public $user;
}
at top of page I'm creating an object:
$a=new a();
$a->get(1234);
and then I'm creating another object from class b.
$b=new b();
but I want to copy all current variables of $a to $b. so class $b would have variable $name with value 1234.
how can I do this?
Add a constructor to b
that takes a parameter of type a
?
class b extends a{
public $user;
function __construct(a $a)
{
parent::__construct($a.name);
}
}
There are good reasons not to do this..
However - some hacks with serialize/deserialize could make an instance of class a class b
function copyDown($obj, $newInstance) {
$data = serialize($obj);
$newData = preg_replace('~(^O:[0-9]+:)"([^"]+")~', '$1"' . $newInstance . '"', $data);
return unserialize($newData);
}
$a = new ClassA();
$b = copyDown($a, 'ClassB');
But be aware that ClassB should inherit from ClassA
I think if you create object of class b by passing the value then you can access the variables of class a in class b as class b is extending class a.
<?php
class a {
private $name;
public function __construct($v){
$this->name=$v;
}
}
class b extends a {
public $user;
}
$b = new b(1234);
var_dump($b);
?>