php类的单继承和trait的使用,实现多继承效果

一、php类名规范:
1>类名可包含字母,数字,下划线,不能以数字开头;
2>类名不区分大小写;
3>类名不能使用关键字;
4>类文件都以.class.php为后缀,使用驼峰法命名,并且首字母大写;

二、实例化类和继承
1>class 声明的类使用new关键字实例化,使用extends 继承父类
2>php中的类是单继承,没有多继承的特性,可以使用traits实现多继承效果
3>trait 可以理解为一组能被不同的类都能调用到的方法集合,但trait 不是类,不能被实例化
trait 可以看做类的部分实现,可以混入一个或多个现有的php类中,其作用有两个:表明类可以做什么;提供模块化实现。trait是一种代码复用技术,为php的单继承限制提供了一套灵活的代码复用机制。

<?php
//父类
class father{
    function callme(){
        echo 'I,m father';
    }
}
//trait
trait brother{
    function callme(){
        echo 'I,m brother';
    }
}
//子类
class children extends father{
    //使用use关键字引入trait 声明的方法/属性集,然后就可以使用啦
    use brother;
    function callme(){
        echo 'I,m children';
    }	

}

$person = new children();
//从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。
//方法调用优先级:自身方法>trait的方法>继承的方法
$person->callme();

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/chailihua0826/article/details/84580990