php - php调用类的最短版本
问题描述
我看到了很多可以用来在 PHP 中调用另一个类中的类的方法,我希望您对调用类的最短版本有意见。
假设我们有一个类名视图和另一个类名控制器
class View
{
private $data = array();
private $render = FALSE;
public function __construct($template , $datas = null)
{
try {
$file = strtolower($template) . '.php';
if (file_exists($file)) {
if($datas > 0) {
foreach($datas as $data) {
array_push($this->data, $data);
}
}
$this->render = $file;
} else {
die('Template ' . $template . ' not found!');
}
}
catch (customException $e) {
echo $e->errorMessage();
}
}
public function __destruct()
{
extract($this->data);
include($this->render);
}
}
和
require_once "system/autoload.php";
class Controller {
function index() {
$view = new View('something');
}
我知道我可以使用
$view = new View('something');
或使用 OOP 和范围并从控制器内部的视图中调用函数,例如
$this->viewFunction();
但是有什么方法可以像这样在控制器内部调用视图类
View('something)
如果不可能,我想让它成为可能的最短版本,或者我必须在编译器内部进行更改,只需给我最短的版本
谢谢你们
解决方案
你当然可以在 PHP 中做到这一点。看看魔术方法,尤其是 __invoke()
class View
{
public function __invoke(string $template)
{
return $template;
}
}
你可以简单地调用它
$view = new View();
$view('my template');
推荐阅读
- python - 以特定时间间隔运行脚本
- android - Android:来自 Firebase 存储的音频流使用了太多数据
- google-slides-api - Google slides API ReplaceAllShapesWithImageRequest:如何确保图像保持相同的形状?
- .net - 使用身份在 asp.net 核心中调试时为当前用户添加或删除角色?
- android - 改造不会序列化我的响应类中的第二个对象
- python - Sklearn 目标数据 - 只有整数标量可以转换为标量索引
- django - 如何将 slug 传递给 Django 中的 URL?
- javascript - Discord 在消息字符串中添加逗号
- json - 在将 XML 转换为 JSON 时如何使用 XSLT 忽略 XML 中的“”?
- vue.js - 如何在 Nuxt Axios API 调用中创建自动相对基本 URL(用于未知部署域)