2014-09-19 54 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

相关问题