Julian
Julian

Reputation: 4666

Why is not possible for a child class to inherit properties class that are set dynamically?

Inheritance of properties is possible when a property is hardcoded. See below:

class ParentObj {   

    protected $familyName = 'Lincoln';   

}   

class ChildObj extends ParentObj {   

    public function __construct() {   
        var_dump($this->familyName);  
    }   
}   

$childObj = new ChildObj();   

// OUTPUT 
string 'Lincoln'

Inheritance of properties is not possible when a property is dynamic. See below:

class ParentObj {   

    protected $familyName; 

    public function setFamilyName($familyName){  
        $this->familyName = $familyName;  
    } 

}   

class ChildObj extends ParentObj {   

    public function __construct() {   
        var_dump($this->familyName);  
    }   
}   

$familyName = 'Lincoln';  
$parentObj = new ParentObj();  
$parentObj->setFamilyName($familyName); 

$childObj = new ChildObj(); 

// OUTPUT
null

So the question is: Why is not possible for a child class to inherit properties class that are set dynamically?

Upvotes: 0

Views: 80

Answers (2)

Gordon
Gordon

Reputation: 316969

The child inherits it's initial state from the parent class. It does not inherit from the concrete parent object instance.

In your first example, "Lincoln" is applicable to all ParentObject instances created. In your second example, it is applicable to the concrete $parentObj only. You are setting it specifically to that instance.

See my answer What is a class in PHP? for a more thorough explanation.

Upvotes: 3

jibsteroos
jibsteroos

Reputation: 1391

If you wanted to access the value of $familyName from all instances(objects), you can define $familyName as static, i.e. create a global class variable.

e.g.

<?php

class ParentObj {

    protected static $familyName;

    public function setFamilyName($familyName){
        self::$familyName = $familyName;
    }

}

class ChildObj extends ParentObj {

    public function __construct() {
        var_dump(self::$familyName);
    }
}

$familyName = 'Lincoln';
$parentObj = new ParentObj();
$parentObj->setFamilyName($familyName);
$childObj = new ChildObj(); // Output: Lincoln

$familyName = 'Lee';
$parentObj->setFamilyName($familyName);
$childObj = new ChildObj(); // Output: Lee

Note of Caution: $familyName is now a global and will change for all instances of this object. This could lead to unexpected results if you ever change the value within the script. Global variables are generally considered a Bad Idea.

Upvotes: 1

Related Questions