PHP - 在子类和父类之间传递变量

时间:2016-03-08 08:38:05

标签: php class var extends

我想知道在父类和子类之间传递变量的最佳方法是什么,并且在类中执行更新此类。 例如,我有这个父类,其中包含子类:

class My_Class {

   public $data;
   public $data2;

   public function __construct() {  
   }

   public function output() {
       $data['key1'] = 1;
       $data['key2'] = 2;
       $data2['key1'] = 'a';
       $data2['key2'] = 'b';
       $child_class = new Child_Class();
       $child_class->output();
       print_r($this->data); // only contains  key1 & key2, I want to get key3 and 4 also
       print_r($this->data2);
   }

}

class Child_Class extends My_Class {

   public function __construct() {  
   }

   public function output() {
       $data  = parent::$data; // want to get data array but it's empty
       $data2 = parent::$data2; // want to get data2 array but it's empty
       this->set_data();
   }

   public function set_data() {
       $this->data['key3'] = 3;
       $this->data['key4'] = 4;
       $this->data['key3'] = 'c';
       $this->data['key4'] = 'd';
   }


}

$class = new My_class();
$class->output();

目前我在父类中执行子类,因为我需要填充父类的主数据。该类将基于某个变量执行子类。

从父级到子级和子级到父级继承和分配变量的正确方法是什么。如果我使用依赖注入来检索extends类中的数据,我该如何将变量分配给父类?

2 个答案:

答案 0 :(得分:1)

"你有一个例子" - 你走了......

<?php
class My_Class {
    public $data = array('key1'=>1, 'key2'=>2);
    public $data2 = array('key1'=>'a', 'key2'=>'b');

    public function output() {
        echo "MyClass::output\r\n";
        print_r($this->data);
        print_r($this->data2);
    }
}


class Child_Class extends My_Class {

    public function __construct() {
        $this->data['key3'] = 3;
        $this->data['key4'] = 4;
        $this->data2['key3'] = 'c';
        $this->data2['key4'] = 'd';
    }

    public function output() {
        echo "Child_Class::output\r\n";
        parent::output();
    }
}

$class = new Child_Class();
$class->output();

打印

Child_Class::output
MyClass::output
Array
(
    [key1] => 1
    [key2] => 2
    [key3] => 3
    [key4] => 4
)
Array
(
    [key1] => a
    [key2] => b
    [key3] => c
    [key4] => d
)

另见:

答案 1 :(得分:0)

我的问题是类型,而不是我写的$this->data$this->$data只是在每个语句的开头都需要$符号。

我的第二个问题是在访问父类上的变量时省略了$this->部分,因此为父类创建了本地范围的变量,该子类不与子类共享,应该使用$this->variable