您的位置 首页 php

PHP中关于trait使用方法的详细介绍

本篇文章主要介绍了PHP中trait使用方法,个人觉得挺不错的,现在分享给大家,也给大家做个参考。一起过来看看吧。下面开始正文。

说通俗点,PHP中使用trait关键字是为了解决一个类既想集成基类的属性和方法,又想拥有别的基类的方法,而trait一般情况下是和use搭配使用的。请看下面的示例代码

<?php    header("Content-type:text/html;charset=utf-8");    trait Drive {                      //使用trait 创建一个基类    public $carName = 'trait';         //定义一个变量    public function driving() {        //定义一个方法    echo "driving {$this->carName}<br>";        }    }    class Person {                    //创建一个基类        public function eat() {         //定义一个方法            echo "eat<br>";            }    }    class Student extends Person {    //创建一个子类继承Person类        use Drive;                      //使用trait定义的类Drive        public function study() {        //定义一个方法            echo "study<br>";            }    }    $student = new Student();     //创建对象    $student->study();            //调用自己定义的方法    $student->eat();              //调用父类方法    $student->driving();          //调用trait定义的类Drive的方法?>

运行效果图如图所示

1.png

上面的例子中,Student类通过继承Person,有了eat方法,通过组合Drive,有了driving方法和属性carName。

如果Trait基类本类中都存在某个同名的属性或者方法,最终会保留哪一个呢?

<?php     header("Content-type:text/html;charset=utf-8");        trait Drive {                  //使用trait定义一个类         public function hello() {    //定义一个方法            echo "我是trait类的方法hello()<br>";        }        public function driving() {            echo "我是trait类的方法driving()<br>"; //定义一个方法        }    }    class Person {                //创建父类        public function hello() {    //定义一个方法            echo "我是父类的方法hello()<br>";        }        public function driving() {      //定义一个方法            echo "我是父类的方法driving()<br>";        }    }    class Student extends Person {         //创建子类继承Person类        use Drive;                           //使用trait定义的类Drive        public function hello() {             //定义一个方法            echo "我是子类的方法hello()<br>";        }      }    $student = new Student();            //创建对象    $student->hello();                    //调用hello方法    $student->driving();                  //调用deiving方法?>

运行效果如图所示

1.png因此得出结论:当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,在这个例子中也就是student的hello()方法覆盖了trait中的hello()方法。而 trait 的方法又覆盖了基类中的方法。在这个例子中,trait的driving()方法就是覆盖了Person类中driving()方法。

如果想了解更多php的相关知识可以到网站的php模块中去学习更多有意思的知识。

以上就是PHP中关于trait使用方法的详细介绍的详细内容,更多请关注求知技术网其它相关文章!

文章来源:智云一二三科技

文章标题:PHP中关于trait使用方法的详细介绍

文章地址:https://www.zhihuclub.com/3902.shtml

关于作者: 智云科技

热门文章

网站地图