首页 > 解决方案 > 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)

如果不可能,我想让它成为可能的最短版本,或者我必须在编译器内部进行更改,只需给我最短的版本

谢谢你们

标签: phpoopbackend

解决方案


你当然可以在 PHP 中做到这一点。看看魔术方法,尤其是 __invoke()

class View
{
    public function __invoke(string $template)
    {
        return $template;
    }
}

你可以简单地调用它

$view = new View();
$view('my template');

推荐阅读