This is not duplicate of this Passing a variable from one php include file to another: global vs. not
I am trying to make a simple php project where I have different file for DB connection(config.php), DB functions(db_functions.php), normal functions(functions.php) and index file(index.php).
I have DB connection set up in config.php -
$link = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_error());
This connection works properly(tested on index.php). DB_HOST and other constants are declared in config.php file. Now, I have my php files connected like this -
functions.php is required(using require) in index.php
db_functions.php is required(using require) in functions.php
config.php is required(using require) in db_functions.php
Now, if I want to use the $link
variable in db_functions.php, it doesn't work. Shows a notice Undefined variable: link in db_functions.php on line 10
.
I am calling the $link
in a function on db_functions.php Declaring global $link
once on db_functions.php doesn't work either. I have to declare global $link
in every function on db_functions.php. This is annoying, is there any way to avoid using it so many times? Or work around without even declaring global?
Thanks in advance