可以从子类访问父类私有属性

时间:2015-11-01 22:00:17

标签: php class oop

<?php
class Parent_Class
{
    //Properties defined
    private $name = "Faizan";
    //Constructor defined
    public function __construct () {
            echo 'The class "',__CLASS__.'" initialized <br>';
        }
    //Methods defined
    public function setName ($name) {
            $this->name = $name;
        }
    public function getName () {
            return $this->name;
        }
    // __toString() Method
    public function __toString () {
            return "<b>".__CLASS__."</b> toString magic method called <br>";
        }
    //Destructor defined
    public function __destruct () {
            echo 'The class "', __CLASS__,'" destroyed <br>';
        }
}
class Child_Class extends Parent_Class
{
    //Parent property override
    //private $name = "Abdullah";
    //Child class constructor override
    public function __construct () {
            parent::__construct();
            echo 'This is the <b>"', __CLASS__, '"</b> constructor. <br>';
        }
    //Child class __toString() override
    public function __toString () {
            parent::__toString();
            return "<b> ". __CLASS__ . "</b> toString() method <br>";
        }
    //Parent methods in class override
    public function setName ($name) {
            $this->name = $name;
        }
    public function getName () {
            return $this->name. " " .parent::getName();
        }
    //Child class destructor override
    public function __destruct() {
            parent::__destruct();
            echo 'The is the <b>"', __CLASS__, '"</b> destructor. <br>';
        }
}
$pObj = new Parent_Class;
echo $pObj->getName()."<br>";
$obj = new Child_Class;
echo $obj;  
echo $obj->getName(),"<br>";
//unset($obj);
$obj->setName("Ali");   
echo $obj->getName(), "<br>";
echo $pObj->getName()."<br>";       
?>

0 个答案:

没有答案