首页 > 解决方案 > 类似于 __construct 但调用类中每个新调用的函数

问题描述

我有以下3个文件:

控制器.php

class inject{
    public function __construct(){
        echo 'I say';
    }
}

模型.php

class say extends inject{
    public function init(){
        echo ' hello ';
        $this->otherFunction();
    }
    public function otherFunction(){
        //parent::__construct(); --> This should't be added manually
        echo ' world ';
    }
}

视图.php

$output = new say();
$output->init(); //UPDATED

如果不修改“say​​”类中的函数(我在上面做了),我希望每次调用函数 init() 时,它都会产生“我说你好,我说世界”。我该怎么做?

演示

标签: phpfunctionclass

解决方案


如果您想在不修改类的情况下为类添加新功能,可以使用装饰器模式。

<?php
class inject{
    public function __construct(){
        echo 'I say';
    }
}

class say extends inject{
    public function init(){
        echo ' hello ';
        $this->otherFunction();
    }
    public function otherFunction(){
        echo ' world ';
    }
}

class DecoratorSay extends say
{
    public function otherFunction() {
        parent::__construct();
        parent::otherFunction();
    }
}

$output = new DecoratorSay();
echo $output->init();

输出

I say hello I say world 

推荐阅读