PHP include_once: import processing i.e. For configuration files

Suppose we have the following structure:

index.php
config.inc.php
\ lib
\ lib \ common.php

In the config.inc.phpset a few parameters such as the database name, user, and co. What is the proper way to access them, i.e. Of the function located in \lib\common.php. Do I need to do include_once("config.inc.php")inside each function?

This does not work if:

  • config.inc.phpincluded once in index.php before including \lib\common.phpthere
  • If it config.inc.phpdefines all the variables before including \lib\common.phpall other files (thus, I would have to include config.inc.phpin all the "central" files at the levelindex.php
  • it does not work if config.inc.phpincluded in the beginning\lib\common.php

Thank you very much - I could not find a solution with Google!

Decision

config.inc.php index.php ( ) ( ). , , !

auto_prepend, n3rd, tkx!

0
5

global , :

$var1 = "muh";
$var2 = "foo";

function test() {
    global $var1;
    echo "var1=$var1; var2=$var2\n";
}

"var1=muh; var2=".

+3

:

include_once("..\\config.inc.php");

common.php.

: , ( , ( "../config.inc.php" ). , config.inc.php , "config.inc.php".

, config.inc.php common.php, require_once() , exit() die(), , , .

EDIT: , . , , , "" , ( ).

:

$var = "Hello World";
function changeVar(){
    $var = "Bye World!";
    echo $var . "\n";
}
changeVar();
echo $var;

:

Bye World!
Bye World!

:

Bye World!
Hello World

, $var INSIDE - , $var, OUTSIDE. :

$var = "Hello World";
function changeVar(){
    global $var;

    $var = "Bye World!";
    echo $var . "\n";
}
changeVar();
echo $var;

:

Bye World!
Bye World!
+2

config.inc.php index.php... , , .

common.php, global , config.inc.php

+1

U auto_prepend, . script , ".autoinc.php", , , , , . . .

0

IMHO, . . . - , "" .

Config , ( XML DOCUMENT_ROOT), , , ,

$dbalias = Config::get('db');
DB::connect($dbalias);
echo $dbalias->user . '@' . $dbalias->host;

, (, SVN). Evereyone , , , .

I'm not sure if this method is the best, but safe and very convenient for code, for reading and support.

0
source

Source: https://habr.com/ru/post/1714872/


All Articles