Home >Backend Development >PHP Problem >Master the correct way to reference configuration files

Master the correct way to reference configuration files

autoload
autoloadOriginal
2021-03-09 13:46:322035browse

1. The use of global

As we all know, global variables cannot be used without modification in methods, as follows:

<?php
   $a=1;
   function Test()
   {
       echo $a;//报错,undefined variable
   }
?>

So We need help from global:

<?php
   $a=1;
   function Test()
   {
       global $a;
       echo $a;//报错,undefined variable
   }
   Test();//输出1

?>

2. Introduce the configuration file

The configuration file is as follows:

<?php       //在根目录下config\config.php
return array(
    //数据库配置
    &#39;database&#39;=>array(
         &#39;type&#39;=>&#39;mysql&#39;,
         &#39;host&#39;=>&#39;localhost&#39;,
         &#39;port&#39;=>&#39;3306&#39;,
         &#39;user&#39;=>&#39;root&#39;,
         &#39;pass&#39;=>&#39;root&#39;,
         &#39;charset&#39;=>&#39;utf8&#39;,
         &#39;dbname&#39;=>&#39;my_database&#39;,
         &#39;prefix&#39;=>&#39;&#39;

    ),
    &#39;system&#39;=>array(
        &#39;error_reporting&#39;=>E_ALL,//错误级别控制,默认显示所有错误
        &#39;display_errors&#39;=>1,     //错误显示控制,1代表显示错误,0代表隐藏错误;
    )
);

?>

is used as follows:

<?php  //在根目录下
function abc(){          
    global $config;
    $config=include &#39;./config/config.php&#39;;
}
function efg(){
    global $config;
    var_dump($config);
}
abc();//调用abc()方法,将配置文件赋值引入
efg();//输出配置文件
echo "<br>";
echo "<pre class="brush:php;toolbar:false">";
var_dump($config);
?>

Recommended: php tutorial,php video tutorial

The above is the detailed content of Master the correct way to reference configuration files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn