Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get non-static variable from inherited class?

In such a case, how to access the property in the first class from the second class?

class First
{
    public $var = 'First Non-Static Property';

    public function __construct()
    {
        echo $this->var;
    }
}

class Second extends First
{
    public $var = 'Second Non-Static Property';

    public function __construct()
    {
        parent::$var;
    }
}

$object = new Second();

Im getting an error;

Fatal error: Uncaught Error: Access to undeclared static property: First::$var in /Applications/MAMP/htdocs/tests/index.php on line 19

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should brush up on OOP, inheritance and overriding. When you create an instance of a class, the created object contains all of the attributes and methods defined in it, as well as any other methods and attributes of it’s parent class which it is extending (as long as they have a scope of public and protected)

In your case, the class "Second" does inherit class "First" BUT it does re-initialize the value of your "var" class property that you initially defined in the First class. Therefore, you’re basically done with accessing the value that var has in the the first class, because you set it to a new value in the child (Second) class.

If you do for some reason want to access it, you can remove the

public $var = 'Second Non-Static Property';

part in the second class, and then in the second class in the constructor have something like:

public function __construct()
{
    echo $this->var;
}

this will print "First Non-Static Property"

and then you can redefine the var property of the Second class as you with after this call.

Second option that comes to mind is you to call the parent constructor

public function __construct()
{
    parent::__construct();
}

That will also print out the "First Non-Static Property".

Some additional mentions of the difference between parent:: and $this-> can be found here
PHP Accessing Parent Class Variable

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading