php - 类似于 __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() 时,它都会产生“我说你好,我说世界”。我该怎么做?
解决方案
如果您想在不修改类的情况下为类添加新功能,可以使用装饰器模式。
<?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
推荐阅读
- sql - 取决于条件的所有可能的项目组合
- c# - 如何通过输入天数获得下一个工作日?
- nginx - 无法在 nginx 上使用散景打开 websocket
- yaml - 如何在 userdata cloudformation 中编写以下命令?
- python - 在从 csv 中提取数据并写入文本文件时需要帮助
- node.js - Node/Express - 如何更改默认根 URL
- r - 删除尾随空格并合并 R 中可能重复的因素
- npm - 解决 npm shrinkwrap peer 无效依赖
- swift - 无法安装“GoogleSignIn”Pod
- python - 为什么我不能在 Pandas 中保留一些变量并重命名变量?