0

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
}
1
  • You can set it in the __construct() function, then it'll be available to use for all the methods. Commented Sep 19, 2014 at 9:45

3 Answers 3

2

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

public function __construct() {
    $this->data = $this->getData();
}
Sign up to request clarification or add additional context in comments.

2 Comments

This will not work as you are overriding the parent class constructor and getData() method is undefined.
Correct @Zeusarm, I tried this and had a suede of errors as I was overrdindg the parent contract as you so rightly point out
1

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

1 Comment

This causes a fata error because it breaks other methods within my class.
0
class Myclass extends AnotherClass{

   protected $array_var;

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

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

2 Comments

A few explaining sentences would be helpful. :-)
I think is clear...when you create the class "Myclass" automatically (with your constructor you have a variable "array_var" populated with the function "getData"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.