简体   繁体   中英

config file in php

我想创建一个用户定义的配置文件,其中包含一些具有常量值的变量,现在我想在我的应用程序的许多页面中访问这些值。如何使用函数使用这些变量。使用类。

You can define this file somewhere and include it or require it.

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

Any variables within this file are accessible in the script that requires / includes it.

Or you can use define as:

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

Now using TEST in all capitals will have the value it was defined as.

Also, if you want them accessible in functions you have three options, pass them as arguments to the function when called or declare as global within function.

//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! 

Well doing it without classes you could use define() to create user based constants to use throughout your application.

EDIT The naming convention for constants are all uppercase chars.

example:

define(DATE, date());

you can call it in your script by calling :

$date = DATE;

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

Alternatively you can save the details in the $GLOBALS array. Remember that this is not completely secure, so use md5() to store passwords or sensitive data.

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

Well there are a couple of ways you can do this

if i have a simple config file like config.ini (it can be htttp://example.com/config.ini, or /etc/myapp/config.ini )

user=cacom
version = 2021608
status= true

this is my function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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