PHP如何为类方法创建辅助函数

时间:2018-04-10 00:50:44

标签: php

我想创建一些使用现有类方法的全局函数。我没有显示getConfig()方法的所有支持功能,但它与我的问题无关:

class Init {

    public function getConfig($type) {
        if (isset($this->config[$type])) {
            return $this->config[$type];
        }

        $file = dirname(__FILE__, 3).'/app/config/'.$type.'.php';
        if (!file_exists($file)) {
            return false;
        }

        $contents = include($file);
        $this->config[$type] = $contents;

        return $this->config[$type];

    } // End getConfig

}

// class Init gets instantiated in my bootstrap file

现在,在我的helpers.php文件中:

function app_config($key) {
    $init = new Init(); // Is there any better way of doing this?
    return $init->getConfig('app')[$key];
}

因此,对于任何给定的请求,帮助函数app_config可以在整个应用程序的20个位置使用。更不用说使用Init类以及其他类的其他辅助函数。

设置这些辅助函数的最佳方法是什么?他们应该一遍又一遍地实例化这些类吗? (这使得具有传递给构造函数的特定参数的类非常困难)

0 个答案:

没有答案