user3770579
user3770579

Reputation: 23

PHP - Predefine an array at the begining of a class for all methods to use

I have a method within a class that returns a single array. This method is called within other methods inside the same class. Rather than keep defining $data at the begining of each method, is there a way og defining it at the begining of the extended class? Here is an example of what I'm trying to achieve [simplified]

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
}

Upvotes: 0

Views: 64

Answers (3)

Zeusarm
Zeusarm

Reputation: 1036

Try to put that assignment in the class constructor:

class MyClass extends AnotherClass {
    protected $variable;

    function __construct()
    {
        parent::__construct();
        $this->variable = $this->getData();
    }

} 

** UPDATE **

You can also try the following

class MyClass extends AnotherClass {
    protected $variable;

    function __construct($arg1)
    {
        parent::__construct($arg1);
        $this->variable = parent::getData();
    }

} 

According to your Parent class you need to pass the needed arguments

Upvotes: 1

Roger Guasch
Roger Guasch

Reputation: 410

class Myclass extends AnotherClass{

   protected $array_var;

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

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

Upvotes: 0

davidkonrad
davidkonrad

Reputation: 85538

Well, maybe I miss something, but normally you would instantiate such variable in a constructor :

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

Upvotes: 2

Related Questions