PHP5でスーパークラスオブジェクトをサブクラスオブジェクトにする

StackOverflow https://stackoverflow.com/questions/1625824

  •  06-07-2019
  •  | 
  •  

質問

<?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のオブジェクトを安全に作成するにはどうすればよいかということです。

役に立ちましたか?

解決

class A
{
  public $property = 'Foobar';
}

class B extends A
{
  public function __construct()
  {
    echo $this->property; // Foobar
  }
}

何か不足していますか? OOPに意図していないことを強制的に実行させようとしている、または継承の理解に問題があるように思えます。

クラスAのすべてのパブリックまたは保護されたメソッドとプロパティは、クラスBで使用できます。直接参照するか(私の例のように)、parent ::構文を使用します。

編集

(著者が質問を明確にした)

クラス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;
    }
  }
}

他のヒント

BはAを拡張しているので、なぜBを作成するだけで始められないのでしょうか?いくつかの追加のプロパティを初期化する必要がある場合、次のようにコンストラクタをオーバーライドできます。

class B extends A {
    public function __construct(){
      parent::__construct(); //calls A's constructor
      $this->Bproperty='somevalue';
    }

}

それでも十分でない場合は、Reflectionをご覧ください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top