- <?php
- /**
- * php 混合器 ,间接实现 类的多继承
- *
- * @author sdm
- */
- class Qing_Mix {
- private $objs = array();
- public function __construct($objs) {
- $this->objs = func_get_args();
- foreach ($this->objs as &$obj) {
- $obj->mix = &$this;
- }
- }
- public function __get($name) {
- foreach ($this->objs as &$obj) {
- if (property_exists($obj, $name)) {
- return $obj->$name;
- }
- }
- }
- public function __set($name, $value) {
- foreach ($this->objs as &$obj) {
- if (property_exists($obj, $name)) {
- return $obj->$name = $value;
- }
- }
- }
- public function __isset($name) {
- foreach ($this->objs as &$obj) {
- if (property_exists($obj, $name)) {
- return true;
- }
- }
- return false;
- }
- public function __call($name, $arguments) {
- foreach ($this->objs as &$obj) {
- if (method_exists($obj, $name)) {
- return call_user_func_array(array($obj, $name), $arguments);
- }
- }
- }
- }
- //测试
- if (__FILE__ == realpath($_SERVER['SCRIPT_FILENAME'])) {
- function Test_Qing_Mix() {
- class Test_Qing_Mix_A {
- public $a = 1;
- function fun1() {
- echo "fun1 called\n";
- }
- }
- class Test_Qing_Mix_B {
- public $b = 1;
- function fun2() {
- echo "fun2 called\n";
- }
- function fun3() {
- echo "will call fun1 called\n";
- //调用当前混合器的 fun1 方法
- $this->mix->fun1();
- }
- }
- $mix = new Qing_Mix(new Test_Qing_Mix_A(), new Test_Qing_Mix_B());
- echo "will call fun1\n";
- //调用混合器的fun1
- $mix->fun1();
- echo "will call fun2\n";
- $mix->fun2();
- $mix->fun3();
- }
- Test_Qing_Mix();
- }
输出结果
will call fun1
fun1 called
will call fun2
fun2 called
will call fun1 called
fun1 called