zoukankan      html  css  js  c++  java
  • PHP实现多继承 trait 语法

    原文地址:http://small.aiweimeng.top/index.php/archives/50.html

    PHP没有多继承的特性。即使是一门支持多继承的编程语言,我们也很少会使用这个特性。在大多数人看来,多继承不是一种好的设计方法。
    但是开发中用到多继承该怎么办呢?
    下面介绍一下使用```trait```来实现php中多继承的问题。

    自PHP5.4开始,php实现了代码复用的方法```trait```语法。

    Trait是为PHP的单继承语言而准备的一种代码复用机制。为了减少单继承的限制,是开发在不同结构层次上去复用method,
    Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。

    需要注意的是,从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。

    先来个例子:

    trait TestOne{
    
        public function test()
        {
            echo "This is trait one <br/>";
        }
    
    }
    
    trait TestTwo{
    
        public function test()
        {
            echo "This is trait two <br/>";
        }
    
    
        public function testTwoDemo()
        {
            echo "This is trait two_1";
        }
    
    }
    
    class BasicTest{
    
        public function test(){
            echo "hello world
    ";
        }
    
    }
    
    
    class MyCode extends BasicTest{
    
        //如果单纯的直接引入,两个类中出现相同的方法php会报出错
        //Trait method test has not been applied, because there are collisions with other trait 
        //methods on MyCode 
        //use TestOne,TestTwo;
        //怎么处理上面所出现的错误呢,我们只需使用insteadof关键字来解决方法的冲突
        use TestOne,TestTwo{
            TestTwo::test insteadof TestOne;
        }
    
    }
    
    
    $test = new MyCode();
    $test->test();
    $test->testTwoDemo();
    

      

    运行结果:

    This is trait two 
    This is trait two_1
    

      

  • 相关阅读:
    海康:无法获取未定义或 null 引用的属性“HWP_***
    mariadb:审计插件
    海康:函数执行结果后以XML方式返回
    海康:java sdk 自定义方法与结构体
    websocket:SecurityError5022
    Java中使用DecimalFormat保留两位小数,同时不保留0
    浅谈js作用域与闭包
    [Go] 分析proto序列化每个字段大小
    MySQL 的全文索引.
    带你了解webpack的使用
  • 原文地址:https://www.cnblogs.com/smallKilts/p/10510024.html
Copyright © 2011-2022 走看看