简体   繁体   English

在Cakephp中,如何从整个应用程序访问数组

[英]In Cakephp, how can I access an array from the whole application

In CakePHP, how can I make an array we use accessible by the whole application? 在CakePHP中,如何创建一个我们可以在整个应用程序中访问的数组? Is there an equivalent of PHP's define() function? 是否有相当于PHP的define()函数?

Use the Configure class. 使用Configure类。

In app/config/bootstrap.php: 在app / config / bootstrap.php中:

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

Then anywhere in your app, eg models, views, controllers, helpers, behaviors, components etc etc just access it using: 然后在您的应用程序中的任何位置,例如模型,视图,控制器,帮助程序,行为,组件等,只需使用以下方法访问它:

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

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

If you don't want to "limit" yourself to what CakePHP gives you, you can either use a global variable (yukk) or simply wrap it in a class: 如果你不想“限制”自己对CakePHP给你的东西,你可以使用全局变量(yukk)或者只是将它包装在一个类中:

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

Or use the singleton-pattern: 或者使用单例模式:

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;
    }
}

Then you can do: 然后你可以这样做:

var_dump(Foo::$bar);

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM