简体   繁体   中英

Variable in php require_once file path

How do you take the following and substitue part of the file path as a variable?

require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/directory2/directory3/file.php';

I want to substiture directory2 with a variable $dir2. Simply inserting the variable as follows does not work?

require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/$dir2/directory3/file.php';

Thanks.

Basic php syntax: strings quoted with ' do not interpolate variables. Use a " -quoted string instead:

require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/$dir2/directory3/file.php";
                                         ^---                                  ^---

or use string concatenation:

require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/' . $dir2 . '/directory3/file.php';

There are two ways to do this in PHP.

require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/'.$dir2.'/directory3/file.php';

Or

require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/$dir2/directory3/file.php";

The difference is in using ' or " for strings. When using ' You need to concatenate variables as in the example and as You already did with $_SERVER['DOCUMENT_ROOT']. When using ", You can put the variables in strings "as is" or even do something like this (useful with arrays):

require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/{$_SERVER["HTTP_HOST"]}/directory3/file.php";

Use " will parse the variable.

"/directory1/$dir2/directory3/file.php"

And instead of depending $_SERVER['DOCUMENT_ROOT'] , you should do something like diranme(__FILE__) or __DIR__ (>= 5.3) to define a root dir.

Single quotes prevent variable substitution. Use double quotes:

require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/$dir2/directory3/file.php";

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