PHP-在类的开头预定义一个数组,供所有方法使用



我在一个类中有一个方法,它返回一个数组。此方法在同一类中的其他方法中调用。与其在每个方法的开头都定义$data,还有没有办法在扩展类的开头定义它?以下是我试图实现[简化]的一个例子

class Myclass extends AnotherClass
{
    protected $data = $this->getData(); // this does not wwork
    public function aMethod()
    {
        $data = $this->getData();
        $data['userName'];
        // code here that uses $data array()
    }
    public function aMethod1()
    {
        $data = $this->getData();
        // code here that uses $data array()
    }
    public function aMethod2()
    {
        $data = $this->getData();
        // code here that uses $data array()
    }
    public function aMethod2()
    {
        $data = $_POST;
        // code here that processes the $data
    }
    // more methods
}

好吧,也许我错过了一些东西,但通常你会在构造函数中实例化这样的变量:

public function __construct() {
    $this->data = $this->getData();
}

尝试将该赋值放在类构造函数中:

class MyClass extends AnotherClass {
    protected $variable;
    function __construct()
    {
        parent::__construct();
        $this->variable = $this->getData();
    }
} 

**更新**

您也可以尝试以下

class MyClass extends AnotherClass {
    protected $variable;
    function __construct($arg1)
    {
        parent::__construct($arg1);
        $this->variable = parent::getData();
    }
} 

根据您的Parent类,您需要传递所需的参数

class Myclass extends AnotherClass{
   protected $array_var;
   public __construct(){
      $this->array_var = $this->getData();
   }
   public function your_method_here(){
      echo $this->array_var;
   }
}

最新更新