学习php面向对象知识小结j(继承,访问控制)

继承(extends)

PHP中继承的特点:PHP中类不允许同时继承多个父类,也就是extends后面只能跟一个父类名称,这个特性被称为PHP的单继承特性

<?php
date_default_timezone_set("PRC");

class People
{
    public $weight = '90kg';

    public function sayWeight()
    {
        echo $this->weight . "\n";
    }
}

class Person extends People
{
    // 类的属性的定义
    public $name = "小明";
    public $age = "18";

    //构造函数的使用
    function __construct($name, $age,$weight)
    {
        $this->name = $name; // $this是php里面的伪变量,表示对象自身
        $this->age = $age;
        $this->weight = $weight;
    }

    //析构函数的使用
    function __destruct()
    {
        echo '--over--';
    }

    //类的方法的定义
    public function sayName()
    {
        echo $this->name . "\n";
    }

    public function sayAge()
    {
        echo $this->age . "\n";
    }
}

$aym = new Person('aym', '20','80kg');
$tom = new Person('tom', '18','100kg');
$aym->sayName();
$tom->sayName();
$tom->sayWeight();
运行结果

Person类继承了People类的weight属性以及sayWeight方法,我们可以直接使用父类的方法

访问控制

1、public的类成员可以被自身、子类和其他类访问 

2、protected的类成员只能被自身和子类访问 

3、private的类成员只能被自身访问

<?php
date_default_timezone_set("PRC");

class People
{
    public $weight = '90kg';

    protected $year = '999';

    public function sayWeight()
    {
        echo $this->weight . "\n";
    }

    public function sayYear()
    {
        echo $this->year. "\n";
    }
}

class Person extends People
{
    // 类的属性的定义
    public $name = "小明";
    private $age = "18";// private 类型的属性不能被对象外部访问,但是可以在对象内部使用

    //构造函数的使用
    function __construct($name, $age,$weight)
    {
        $this->name = $name; // $this是php里面的伪变量,表示对象自身
        $this->age = $age;
        $this->weight = $weight;
    }

    //析构函数的使用
    function __destruct()
    {
        echo '--over--';
    }

    //类的方法的定义
    public function sayName()
    {
        echo $this->name . "\n";
    }

    public function sayAge()
    {
        echo $this->age . "\n";
    }
}

$aym = new Person('aym', '20','80kg');
$tom = new Person('tom', '18','100kg');
$aym->sayName();
$tom->sayName();

//访问受保护的属性
echo $aym->sayAge();

//访问私有属性
$tom->sayYear();

直接访问受保护属性和私有属性会导致错误

echo $aym->age;
echo $aym->year;

致命错误,不能直接访问私有属性( Cannot access private property Person::$age)

//访问受保护的属性
echo $aym->sayAge();
//访问私有属性
$tom->sayYear();

 访问成功

猜你喜欢

转载自www.cnblogs.com/carefulyu/p/12652617.html
今日推荐