在程序项目庞大,面向过程式的编程方法会使得程序越来越难维护,代码重复利用率低下等。而面向对象开发帮我们解决了这些难题,使得程序组织更为清晰,更容易维护。
下面是类的封装和调用:
class Test{
protected $name;
protected $sex;
public function setName($name)
{
$this -> name = $name;
}
public function setSex($sex)
{
$this -> sex = $sex;
}
public function say()
{
echo '这个人是'.$this -> name.',他是'.$this -> sex.'人';
}
}
$test = new Test;
$test -> setName('云路');
$test -> setSex('男');
$test -> say();
输出结果:
当你封装好了一个类后,你可以无限的使用的,在代码中你只需要引入它,便可以使用它,满足你某项需求,当你发现它的功能并不能完全满足你时,你可以使用类的继承,让你不影响当前类的结构的情况下,丰富它。
下面展示了类的继承:
class Father
{
protected $name = '云小璐';
protected $sex = '女';
public function say()
{
echo '这个人是'.$this -> name.',他是'.$this -> sex.'人';
}
}
class Son extends Father
{
public function setName($name)
{
$this -> name = $name;
}
public function setSex($sex)
{
$this -> sex = $sex;
}
}
$test = new Son;
$test -> setName('云路');
$test -> setSex('男');
$test -> say();
输出结果:
上面Son这个类继承了类Father,Father就是Son这个类的父类,Son这个类可以使用父类中的方法和变量。当你发现一个类的功能不能满足你的要求的时候,你又不想修改它,怕影响其他功能时,你就可以使用类的继承,来丰富你的类。