【发布时间】:2014-09-02 17:36:39
【问题描述】:
我有一个利用单例原理的类,并且我有允许链接的方法。最后,您必须调用 output() 方法来呈现该类,但我想知道是否有任何方法可以自动执行此操作。我试过使用 __destruct,但它处理得很晚。我需要在脚本退出之前完成它。
class View {
private static $_instance = null,
$_view;
public static $data;
private static function getInstance()
{
// Instantiate the class
if( self::$_instance === null ){
self::$_instance = new self;
}
return self::$_instance;
}
public static function make( $view )
{
$instance = self::getInstance();
$file = explode( '.', $view );
$file = DIR . 'core/views/' . $file[0] . '/' . $file[1] . '.php';
self::$_view = $file;
return $instance;
}
public function with($data)
{
self::$data = $data;
return $this;
}
}
它会像这样使用:
return View::make($view)->with($data);
【问题讨论】:
-
PHP 中的单例与暑假穿雪鞋一样有意义:PHP 是无状态的,单例只是伪装的全局变量。为什么不创建三个全局函数,然后将您需要的内容传递给它们?
-
你应该看看 Laravel 源代码,因为它看起来像是你在尝试模仿它。
-
@true 哈哈,好猜!我正在尝试在 WP 插件中利用它的结构。