PHP 面向对象基础:继承父类 1 个改进

子类继承父类所有共有的和受保护的属性和方法,继承关键字为 extends 。一个类不能同时继承多个类,也就是说一个类只能继承唯一的类。可参见封装性 publicprotectedprivate

class Parents
{
    public $name = 'parents';
    protected $age = '55';

    public function getName()
    {
        echo 'This is parents.' . $this->name . '<br />';
    }

    protected function getAge()
    {
        echo 'Parents\' age is ' . $this->age . '<br />';
    }
}

子类获得父类所有共有和受保护的属性和方法

class Son extends Parents
{
    public function showAll()
    {
        echo 'Coming form ' . $this->name . '<br />';
        echo 'Age is ' . $this->age . '<br />';
        $this->getName();
        $this->getAge();
    }
}

$son = new Son();
$son->showAll();

输出

Coming form parents.
Age is 55.
This is parents.
Parents' age is 55.
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!