我有一个包含全局使用方法的类,并通过扩展类来使用它们:
App.php
final class App extends Core {
// The app class handles routing and basically runs the show
}
core.php中
abstract class Core {
public function __construct() { // Here we bring in other classes we use throughout the app
$this->Db = new Db($this);
$this->Mail = new Mail($this);
}
// Then we define multiple methods used throughout the app
public function settings($type) {
// You see this used by the model below
}
}
的index.php
$App = new App(); // This fires up the app and allows us to use everything in Core.php
到目前为止,这一切都很棒,因为所有内容都是在$App
内从整个网站处理的。但是,在我的MVC结构中,模型需要从数据库中提取数据,以及检索Core
中包含的所有其他设置。我们不需要模型使用整个$App
类,但我们需要Core
。
MyModel.php
class MyModel extends Core {
public function welcome() {
return 'Welcome to '.$this->settings('site_name');
}
}
MyModel.php
发挥作用后,Core
构造函数将再次运行。如何防止Core
构造函数被运行两次?
答案 0 :(得分:1)
您可以在core
类中使用静态实例并重复使用它。
abstract class Core {
public static $instance; //create a static instance
public function __construct() { // Here we bring in other classes we use throughout the app
$this->Db = new Db($this);
$this->Mail = new Mail($this);
self::$instance = $this; // initialise the instance on load
}
// Then we define multiple methods used throughout the app
public function settings($type) {
// You see this used by the model below
}
}
在模型类中,像这样使用它
class MyModel extends Core {
public function welcome() {
$_core = Core::instance; // get the present working instance
return 'Welcome to '.$_core->settings('site_name');
}
}
你可以看看这个singleton reference 另外,您可以查看此答案explain-ci-get-instance