2014-09-19 55 views
0

我在返回單個數組的類中有一個方法。此方法在同一類內的其他方法中調用。在每個方法的開始時不是定義$data,而是在擴展類的開始處定義它嗎?下面是我想要實現[簡化]PHP - 在所有使用方法的類的開頭預定義一個數組

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 
} 
+0

你可以將它設置在__construct()函數,那麼它可以用於所有的方法。 – Erik 2014-09-19 09:45:01

回答

1

嘗試把在類的構造函數,賦值一個例子:

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(); 
    } 

} 

根據你的P的arent類,你需要傳遞需要的參數

+0

這會導致一個fata錯誤,因爲它會破壞我的類中的其他方法。 – user3770579 2014-09-19 10:08:17

+0

我已經更新了答案,請嘗試這個 – Zeusarm 2014-09-19 10:22:22

2

好吧,也許我錯過了什麼,但通常你會在構造函數實例化這樣的變量:

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

這不會工作,因爲您重寫父類的構造函數,並且getData()方法未定義。 – Zeusarm 2014-09-19 09:56:20

+0

正確@Zeusarm,我試了這個,並有一個錯誤的麂皮,因爲我過分地強調父母合同,所以你正確地指出 – user3770579 2014-09-19 10:04:00

0
class Myclass extends AnotherClass{ 

    protected $array_var; 

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

    public function your_method_here(){ 
     echo $this->array_var; 
    } 
} 
+0

一些解釋句子會有幫助。 :-) – 2014-09-19 10:43:06

+0

我覺得很清楚...當你自動創建類「Myclass」(用你的構造函數你有一個變量「array_var」填充函數「getData」 – 2014-09-22 07:22:19

相關問題