<?php
class Person
{
public $name;
private $age;
protected $sex;
public function __construct($name='peng',$age=18,$sex='男')
{
$this->name=$name;
$this->age=$age;
$this->sex=$sex;
}
public function eat($food='菜')
{
return $this->name.'喜欢'.$food;
}
//创建一个访问私有属性的公共接口
public function getAge()
{
return $this->name.'年龄是:'.$this->age;
}
//创建一个访问受保护的公共接口
public function getSex()
{
return $this->name.'性别是:'.$this->sex;
}
}
class Woman extends Person
{
//创建子类自己的属性
public $job;
//创建子类的构造方法,它会自动继承父类,可以删除父类中的构造器的
public function __construct($name='peng',$job = 'song')
{
parent::__construct($name);//导入父类中的构造方法(器)
$this->job=$job;//初始化当前类(Woman)中的属性
}
//在子类中创建自己的方法
public function getJob()
{
return $this->name.'的工作是:'.$this->job;
}
//在子类中重写父类中的方法,实现多态
public function eat($food='肉')
{
return $this->name.'喜欢'.$food;
}
//在子类中不能创建同名方法来访问父类的私有属性
public function getAge()
{
// return $this->name.'的年龄是'.$this->age.'岁啦~~<br>';
}
//创建访问受保护属性的公共接口 不仅能访问还能改写
public function getSex()
{
// return parent::getSex(); // TODO: Change the autogenerated stub
return $this->name.'性别是:'.$this->sex;
}
}
echo (new Woman)->eat();//适合于临时或一次性访问对象方法
echo '<hr>';
$woman =new Woman('LUCY');
echo $woman->eat('老北京鸡肉卷');
echo '<hr>';
echo (new Woman('lili','shopping'))->getJob();
echo '<hr>';
echo (new Person())->getAge();//父类对象调用父类私有属性
echo '<hr>';
echo (new Woman())->getAge();//子类对象调用父类私有属性不能访问
echo '<hr>';
echo (new Person())->getSex();
echo '<hr>';
echo (new Woman('haimei','play'))->getSex();图:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号