php类可以多继承吗,PHP实现多继承

方法一

自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。

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

Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。

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

trait traitTestOne{

public function test(){

echo "This is trait one
";

}

public function testOne(){

echo "one
";

}

}

trait traitTestTwo{

// public function test(){

// echo "This is trait two";

// }

public function testTwo(){

echo "two
";

}

}

class basicTest{

public function test(){

echo "hello world\n";

}

}

class myCode extends basicTest{

use traitTestOne,traitTestTwo;

}

$test = new mycode();

$test->test();

$test->testOne();

$test->testTwo();

输出:

This is trait one

one

two

方法二

class Parent1 {

function method1() {}

function method2() {}

}

class Parent2 {

function method3() {}

function method4() {}

}

class Child {

protected $_parents = array();

public function Child(array $parents=array()) {

$this->_parents = $parents;

}

public function __call($method, $args) {

// 从“父类"中查找方法

foreach ($this->_parents as $p) {

if (is_callable(array($p, $method))) {

return call_user_func_array(array($p, $method), $args);

}

}

// 恢复默认的行为,会引发一个方法不存在的致命错误

return call_user_func_array(array($this, $method), $args);

}

}

$obj = new Child(array(new Parent1(), new Parent2()));

print_r( array($obj) );die;

$obj->method1();

$obj->method3();

方法三

interface testA{

function echostr();

}

interface testB extends testA{

function dancing($name);

}

class testC implements testB{

function echostr(){

echo "接口继承,要实现所有相关抽象方法!";

echo "
";

}

function dancing($name){

echo $name."正在跳舞!";

}

}

$demo=new testC();

$demo->echostr();

$demo->dancing("模特");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值