简体   繁体   中英

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?

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.

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

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM