<?php
class A{
//many properties
protected $myProperty1;
protected $myProperty2;
protected $myProperty3;
public function __construct(){
$this->myProperty1='some value';
$this->myProperty2='some value';
$this->myProperty3='some value';
}
public function getProperty1(){
return $this->myProperty1;
}
public function getProperty2(){
return $this->myProperty2;
}
public function getProperty3(){
return $this->myProperty3;
}
//edited: I added some setters, meaning that the object returned from the functions may already have these properties altered
public function setProperty1($p){
$this->myProperty1=$p;
}
public function setProperty2($p){
$this->myProperty2=$p;
}
public function setProperty3($p){
$this->myProperty3=$p;
}
}
class B extends A{
private $myProperty4;
public function __construct(A $a){
$this=$a; //this line has error,it says $this cannot be re-assigned
$this->myProperty4='some value';
}
public function getProperty4(){
return $this->myProperty4;
}
}
//$a = new A();
$a = someClass::getAById(1234); //edited: $a is returned by a function (I cannot modify it)
$b= new B($a); //error
?>
我想通过将A的对象传递给B的构造函数来创建B的对象,如您所见,我无法重新分配$ this变量。我不允许修改A类,当A中有很多属性时,在B的构造函数中做这样的事情是很乏味的:
public function __construct(A $a){
parent::__construct();
$this->myProperty1=$a->getProperty1();
$this->myProperty2=$a->getProperty2();
$this->myProperty3=$a->getProperty3();
$this->myProperty4='some value';
}
我的问题是,如何使用A的对象以最少的编码安全地创建B类对象?
答案 0 :(得分:3)
class A
{
public $property = 'Foobar';
}
class B extends A
{
public function __construct()
{
echo $this->property; // Foobar
}
}
我错过了什么吗?这听起来像是你试图强迫OOP做一些不打算做的事情,或者你在理解继承方面遇到了麻烦。
A类中的每个公共或受保护的方法和属性都可以在B类中使用。可以通过直接引用它(如在我的示例中)或使用parent :: syntax。
(作者澄清问题)
如果可以访问A类的属性,您可以使用类似下面的内容将它们复制到B类
class B
{
public function __construct()
{
$a = new A(); // Or however A is instantiated
foreach(get_object_vars($a) as $key => $value)
{
$this->$key = $value;
}
}
}
答案 1 :(得分:0)
由于B扩展了A,为什么不直接创建B?如果你需要初始化一些额外的属性,你可以像这样覆盖构造函数:
class B extends A {
public function __construct(){
parent::__construct(); //calls A's constructor
$this->Bproperty='somevalue';
}
}
如果这还不够好,那么你可能想看一下反思。