PHP:如何防止扩展类的多个实例

时间:2016-12-22 14:12:20

标签: php

我有一个包含全局使用方法的类,并通过扩展类来使用它们:

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构造函数被运行两次?

1 个答案:

答案 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