skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. You access parent class non-static attributes like this:

    <?php
    class First
    {
        public $var2 = 'First Non-Static Property';
    
        public function __construct()
        {
            echo $this->var2;
        }
    }
    
    class Second extends First
    {
        public $var = 'Second Non-Static Property';
    
        public function __construct()
        {
            echo $this->var2;
        }
    }
    
    $object = new Second();
    ?>
    

    If you access variable named var then it will gonna return child class string due to overloading, so if you give different name to variable then you access parent public and protected non-static variables like this.

    Hope this is helpful

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search