So I’ve seen some controversy on passing variables from file to file with PHP. What is the “best way” to do it?
Currently, I’ve got a setup like this
FILE 1:
<? $foo = 'somethingCoolHere';
$bar = 'nothingLameThere'; ?>
FILE A:
<? include('/link/to/file1.php');
printf('stuff' .$foo. 'stuff'); ?>
FILE B:
<? include('/link/to/file1.php');
printf('stuff' .$foo. 'stuff');
printf('stuff' .$bar. 'stuff'); ?>
This works, ‘alright’. But if someone wants to expand on what I’ve got, they may need to remember to include the “include” on the top line to get the variables to work. Is there a “better practice” or “best practice” way vs what I’m doing now?
Personally (not sure if others will agree), I would use absolute paths when including files. And I would have those paths sit in constants. Why? Because if I ever needed to change a path (say I moved a file or something) I would not have to go through every file to change the path, but instead, just the file where the constants were defined.
An example:
constant.php
Then include constant.php in any file you need to use the constants:
something.php:
I’m not saying that method is the best practice, but it would just be something I would do in just about all my projects. And I can’t see anything wrong with it either.