-2

I have a weird problem in PHP. I have two classes, one extending another. The problem is that i when I try to access a variable in the parent class (via a getVar() method), it returns undefined, even though it had been already defined in the parent's constructor.

class HttpClient
{
    private $errorList;

    public function __construct()
    {
        $errorList = [];
    }

    public function getHttpErrorList() { return $errorList; }

    //...
}
class Twitter extends HttpClient 
{
    public function __construct()
    {
        parent::__construct();

        //..
    }

    public function getMessages()
    {   
        //...

        var_dump($this->getHttpErrorList()); //returns undefined variable!
    }

What is the cause of this problem and how do I solve it?

yivi
  • 42,438
  • 18
  • 116
  • 138
Lucca Bibar
  • 141
  • 1
  • 1
  • 10

1 Answers1

1

Defining $errorList=[] inside your constructor is defining a local variable to the constructor. I.e. variable $errorList is undefined in method getHttpErrorList() - if you want access to $errorList at the object level, you need to change it to $this->errorList inside your constructor and in method getHttpErrorList().

<?php
class HttpClient
{
    private $errorList;

    public function __construct()
    {
        $this->errorList = []; // change to $this->errorList
    }

    public function getHttpErrorList() { return $this->errorList; } // change to $this->errorList

    //...
}

class Twitter extends HttpClient
{
    public function __construct()
    {
        parent::__construct();

        //..
    }

    public function getMessages()
    {
        //...

        var_dump($this->getHttpErrorList()); //outputs array(0) {}
    }
}

$twit = new Twitter();
$twit->getMessages(); // output: array(0) { }
lovelace
  • 1,195
  • 1
  • 7
  • 10