从实例获取父类到子类的值

时间:2015-04-11 04:10:13

标签: php class oop inheritance parent-child

我有一个具有$name属性的人员类和一个具有$officer_name属性的官员类。我需要能够从人员类到官员类获得$name属性。在这种情况下,它应该具有" Major Blake"的输出。我是否需要为我做一个军官类的实例才能回应这个?

class person {
    protected $name;

    private function set_name($fv_name) {       
        $this->name = $fv_name;
    }

    public function get_name() {        
        return $this->name;
    }

    function __construct($fv_name) {        
        $this->set_name($fv_name);
    }
}

class officer extends person {

    private function give_rank(){
        return "Major ";
    }

    function __construct() {        
        echo $officer_name = $this->give_rank() . parent::get_name();
    }
}

$iv_person = new person("Blake");

1 个答案:

答案 0 :(得分:0)

请尝试以下代码: 你的班级:

<?php
class person {
    protected $name;

    private function set_name($fv_name) {       
        $this->name = $fv_name;
    }

    public function get_name() {        
        return $this->name;
    }

    function __construct($fv_name) {        
        $this->set_name($fv_name);
    }
}

class officer extends person {

    private function give_rank(){
        return "Major ";
    }

    function __construct($fv_name) {
        parent::__construct($fv_name);
    }

    function output(){      
        return $this->give_rank().parent::get_name();
    }
}

你的电话:

$iv_person = new officer("Blake");  
echo $iv_person->output();