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\n";
    }

}


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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
将 Config 类改写为继承 trait 的方法可以使代码更加灵活,可以在不同的场景中复用 trait,同时也可以让代码更加清晰。下面是一个将 Config 类改写为继承 trait 的示例: ```scala import scopt.OptionParser trait Config { def input: String def output: String def verbose: Boolean } case class MyAppConfig(input: String, output: String, verbose: Boolean) extends Config object MyApp { def main(args: Array[String]): Unit = { val parser = new OptionParser[Config]("my-app") { opt[String]("input") .required() .action((value, config) => config.asInstanceOf[MyAppConfig].copy(input = value)) .text("input file path") opt[String]("output") .required() .action((value, config) => config.asInstanceOf[MyAppConfig].copy(output = value)) .text("output file path") opt[Unit]("verbose") .action((_, config) => config.asInstanceOf[MyAppConfig].copy(verbose = true)) .text("enable verbose output") } parser.parse(args, MyAppConfig("", "", false)) match { case Some(config) => // 执行你的代码,使用 config.input、config.output、config.verbose 等参数 case None => // 解析失败,输出错误信息 } } } ``` 在上面的示例中,我们将 Config 类改写为一个 trait,并定义了一个 case class MyAppConfig 来实现trait。我们在 OptionParser 中使用 Config 类型而不是 MyAppConfig 类型。在 `action` 方法中,我们使用 `asInstanceOf` 方法将 Config 类型转换为 MyAppConfig 类型,并更新相应的参数值。最后,在 `parser.parse` 方法中解析命令行参数,并根据解析结果执行相应的代码。 需要注意的是,在使用 trait 的方法中,我们需要在 trait 中定义所有的参数,并在实现类中实现这些参数。如果 trait 中定义了很多参数,而实现类只需要其中的一部分,那么可以考虑将 trait 拆分成多个小的 trait,使代码更加清晰。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值