简体   繁体   中英

how to access a php variable inside a function from an included file

I have a file called test1.php with lots of variable and some function definitions. I am trying to include this file to one another file called test2.php and use the variables and the functions.

test1.php

$i = "a";
$ii = "b";
$iii = "c";
function test1a(){ return "lol";  }

test2.php

function test2a(){ include 'test1.php'; return $i; }
function test2b() { include 'test1.php'; return test2c(); }
function test2c(){ include 'test1.php'; return $iii; }
function test2d() { include 'test1.php'; return test1a(); }

index.php

include 'test2.php'
echo test2a(); 
echo test2b(); 
echo test2c();
echo test2d();

Reason:

I have the same code base in two different servers. Only the test2.php file will be different.Each server will have different values inside the test2.php but with same variable name. test2.php will act somewhat like a localization file.

My problem is some of the variables or not showing up. Is there a better way to do this. I don't want to include the file in every function.

Thanks.

Just do it the other way round:

put all the different variables into one file in to an array, without any functions:

//config.php
$config['setting1'] = "val1";
$config['setting2'] = "val2";
$config['setting3'] = 42;
...

and further:

//index.php
include_once("config.php");
echo $config['setting1'];
....

now you may have different configs on different servers w/o need to change any functions.

You are trying to include file with one function several times. Functions are always global. So second include gives you an fatal error Fatal error: Cannot redeclare test1a() (previously declared in [..]) .

You should put this function to separate file and use include_once.

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