I face a strange problem including php files. Let me show you the code:
// constants.php
$MYSQL_HOST_PORT = 'localhost:3306';
// functions.php
include 'constants.php';
function getVar() {
echo $MYSQL_HOST_PORT;
}
// doSth.php
include 'functions.php';
echo $MYSQL_HOST_PORT; // The variable is visible and echoed normally as expected!
echo getVar(); // The variable is not echoed! its "".
Any ideas ?
For one, the echo
in echo getVar();
won't ever print anything, because getVar
doesn't return a value.
Secondly, if you (for some reason) want getVar()
itself to work correctly, you need to add a global $MYSQL_HOST_PORT;
line, to make it look for $MYSQL_HOST_PORT
in the global scope.
Rather than globalising the $MYSQL_HOST_PORT
variable, why not simply make it a constant?
// constants.php
define('MYSQL_HOST_PORT', 'localhost:3306');
Provided constants.php
is included, you can reference the MYSQL_HOST_PORT
constant anywhere.
As indicated in zerocrate's answer , the issue is a scoping one. The enclosed scope of the getVar()
function does not include $MYSQL_HOST_PORT
.
One thing that I can see wrong is that with the line echo getVar();
you are not getting a return value from the function so you can simply write getVar();
by itself.
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.