问答详情
源自:4-2 访问控制-PHP面向对象编程

为什么我在父类里定义一下private属性,通过子类继承,可在外面访问,


class Human{
    private   $height;        
}
class Player extends Human {
    protected $age;
    function __construct($name,$height){
         $this->name = $name;
         $this->height = $height;
         }
}
$joden=new Player('joden','25');
echo $joden->height;

提问者:Isset 2014-11-14 16:01

个回答

  • 凯jl
    2014-12-22 22:34:38

    Play的构造方法中这句代码:

    $this->height = $height;

    相当于给player增加了一个height属性...

  • 凯jl
    2014-12-22 22:33:38

    class Human{

        private   $height;

        public function setHeight($h){

        $this->height=$h;

       

        }

        public function printHeight(){

        echo "Human height:".$this->height;

        }

    }

    class Player extends Human {

        protected $age;

        function __construct($name,$height){ 

             $this->name = $name;

             $this->height = $height;

             }

    }

    $joden=new Player('joden','25');

    echo 'Player Heihgt:'.$joden->height;

    echo '<br>';

    echo '调用 Human 方法设置Human 的私有height:<br>';

    echo $joden->setHeight(30);

    echo $joden->printHeight();

    echo '<br>';

    echo '再次打印Player的Heihgt:'.$joden->height;