【问题标题】:In Cakephp, how can I access an array from the whole application在 Cakephp 中,如何从整个应用程序访问数组
【发布时间】:2009-05-25 22:28:51
【问题描述】:

在 CakePHP 中,如何使我们使用的数组可供整个应用程序访问?有没有相当于 PHP 的 define() 函数?

【问题讨论】:

    标签: php arrays cakephp


    【解决方案1】:

    使用配置类。

    在 app/config/bootstrap.php 中:

    配置::write('myArray', array(1,2,3));

    然后在您的应用中的任何位置,例如模型、视图、控制器、助手、行为、组件等只需使用以下方式访问它:

    $myArray = Configure::read('myArray'); // $myArray 将包含数组(1,2,3)

    【讨论】:

    • 尼尔是正确的。但请记住,像这样在全球范围内共享数据可能是糟糕设计和数据流的重要指标。所以要明智地使用它。
    【解决方案2】:

    我通常使用位于“config”文件夹中的“bootstrap.php”文件。

    【讨论】:

      【解决方案3】:

      如果您不想“限制”自己使用 CakePHP 提供的功能,您可以使用全局变量 (yukk) 或简单地将其包装在一个类中:

      class Foo {
          public static $bar = { 3, 7, 42 };
      }
      

      或者使用单例模式:

      class Foo {
          private static $instance = null;
          public $myVar;
      
          private function __construct() {
              $this->myVar = { 3, 7, 42 };
          }
      
          public static function getInstance() {
              if (self::$instance == null) {
                  self::$instance = new self();
              }
              return self::$instance;
          }
      }
      

      那么你可以这样做:

      var_dump(Foo::$bar);
      

      var_dump(Foo::getInstance()->myVar);
      

      【讨论】:

      • 好吧,我在 bootstrap.php 中同时使用了一些,我设置了单例模式。非常感谢你们
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 2013-05-18
      • 2015-05-30
      • 2019-08-17
      • 1970-01-01
      相关资源
      最近更新 更多