Variable en la ruta del archivo php require_once

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';

Gracias.

preguntado el 09 de marzo de 12 a las 15:03

4 Respuestas

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';

respondido 09 mar '12, 15:03

Utilizan " will parse the variable.

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

And instead of depending $_SERVER['DOCUMENT_ROOT'], deberías hacer algo como diranme(__FILE__) or __DIR__ (>= 5.3) to define a root dir.

respondido 09 mar '12, 15:03

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";

Respondido el 06 de enero de 15 a las 17:01

Single quotes prevent variable substitution. Use double quotes:

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

respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.