【问题标题】:config file in phpphp中的配置文件
【发布时间】:2011-04-24 18:45:34
【问题描述】:

我想创建一个用户定义的配置文件,其中包含一些具有常量值的变量,现在我想在我的应用程序的许多页面中访问这些值。如何使用函数使用这些变量..什么是最好的方法在不使用类的情况下执行此操作。

【问题讨论】:

  • 你应该尝试接受更多的答案,因为 22% 很低,不会激励人们回答你...
  • 为什么不使用类?要求人们保持两行(一行在顶部,一行在底部)以将所有配置包装在一个类定义中应该不会比要求他们首先使用 PHP 更难......

标签: php class function code-reuse


【解决方案1】:

您可以在某处定义此文件并包含它或需要它。

require_once("path/to/file/config.php"); 

此文件中的任何变量都可以在requires/includes 它的脚本中访问。

或者你可以使用定义为:

define("TEST", "10");    //TEST holds constant 10 

现在在所有大写字母中使用 TEST 将具有其定义的值。

此外,如果您希望它们在函数中可访问,您有三个选项,在调用时将它们作为参数传递给函数或在函数内声明为全局。

//example 1
require_once("path/to/file/config.php"); 
function testFunction($var){
   echo $var." inside my function";   //echos contents of $var 
}

//now lets say a variable $test = 10; was defined in config.php
echo $test;    //displays "10" as it was defined in the config file.  all is good
testFunction($test);  //displays "10 inside my function" because $test was passed to function


//example 2
require_once("path/to/file/config.php"); 
function testFunction2(){
   global $test; 
   echo $test; //displays "10" as defined in config.php 
}

//example 3
define("TEST", "10");
echo TEST; // outputs "10"
//could have these constants defined in your config file as described and used above also! 

【讨论】:

    【解决方案2】:

    在没有类的情况下做得很好,您可以使用define() 创建基于用户的常量,以便在整个应用程序中使用。

    编辑 常量的命名约定都是大写字符。

    示例:

    define(DATE, date());
    

    你可以在你的脚本中调用它:

    $date = DATE;
    

    http://php.net/manual/en/function.define.php

    或者,您可以将详细信息保存在 $GLOBALS 数组中。请记住,这并不完全安全,因此请使用md5() 来存储密码或敏感数据。

    【讨论】:

    • md5 不用于存储密码。
    • 大声笑我知道 ;) 我的回答可能有点模棱两可,抱歉。我的意思是 md5() $GLOBALS 数组中的任何敏感数据。
    • Globals 的安全性不亚于使用define。此外,md5() 有效地破坏了它所处理的数据,使其无用,除了检查存储在其他地方的数据是否相同。
    【解决方案3】:

    当您使用常量时,define() 是有意义的,但您也可以使用 ini files 作为替代方案。

    【讨论】:

      【解决方案4】:

      有几种方法可以做到这一点

      【讨论】:

        【解决方案5】:

        如果我有一个简单的配置文件,比如 config.ini(可以是 htttp://example.com/config.ini 或 /etc/myapp/config.ini)

        user=cacom
        version = 2021608
        status= true
        

        这是我的功能:

        function readFileConfig($UrlOrFilePath){
        
            $lines = file($UrlOrFilePath);
            $config = array();
            
            foreach ($lines as $l) {
                preg_match("/^(?P<key>.*)=(\s+)?(?P<value>.*)/", $l, $matches);
                if (isset($matches['key'])) {
                    $config[trim($matches['key'])] = trim($matches['value']);
                }
            }
        
            return $config;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-13
          • 1970-01-01
          • 2022-06-22
          • 1970-01-01
          • 2012-06-15
          • 2011-12-02
          • 2013-01-23
          • 2013-05-13
          相关资源
          最近更新 更多