php用反射实现多继承

本文介绍了一种在PHP中实现多重继承的方法,通过自定义类`multi_extends`来模拟多重继承的行为,允许一个类从多个基类继承属性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
class multi_extends {
	public function __construct() {
		$this->_init_extends ();
	}
	protected function _init_extends() {
		if (property_exists ( $this, '_extends' )) {
			$extends = &$this->_extends;
			foreach ( $extends as $class ) {
				$this->_extends ( $class );
			}
		}
	}
	public function _extends($class_name) {
		// 分析目标
		$ref = new ReflectionClass ( $class_name );
		
		// 继承公共属性
		$property_list = $ref->getProperties ( ReflectionProperty::IS_PUBLIC );
		foreach ( $property_list as $property ) {
			$property_name = $property->name;
			$property_value = $property->getValue ( new $class_name () );
			if ($property_name === '_extends') {
				foreach ( $property_value as $c ) {
					$this->_extends [] = $c;
				}
			} else {
				if (! property_exists ( $this, $property_name )) {
					$this->{$property->name} = $property_value;
				}
			}
		}
		
		// 继承公共方法
		$method_list = $ref->getMethods ( ReflectionMethod::IS_PUBLIC );
		foreach ( $method_list as $method ) {
			$this->_extends_method [$method->name] = $method->class;
		}
	}
	function __call($m, $a) {
		if ($c = $this->_extends_method [$m]) {
			eval ( "$c::$m(" . '$a' . ");" );
		}
	}
}

header ( 'content-type:text/html;charset=utf-8' );
class a {
	public $a = 5;
	public function say_name() {
		echo '我叫' . $this->name . '<br>';
	}
}
class b {
	function say_age() {
		echo '我今年' . $this->age . '岁<br>';
	}
}
class c extends multi_extends {
	public $_extends = array (
			'a',
			'b' 
	);
	public function say_hellow() {
		echo 'hellow ' . $this->name . '<br>';
	}
}
class d {
	function say_goodbye() {
		echo 'goodbye ' . $this->name . '<br>';
	}
}
class persion extends multi_extends {
	public $_extends = array (
			'c',
			'd' 
	);
	public $name = "熊宝山";
	public $age = "20";
}

// 执行继承后的方法
$o = new persion ();
$o->say_name ();
$o->say_age ();
$o->say_hellow ();
$o->say_goodbye ();

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值