0

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 -

  1. functions.php is required(using require) in index.php

  2. db_functions.php is required(using require) in functions.php

  3. 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

b0xed
  • 72
  • 9
  • 2
    yes you have to use the GLOBAL key word in every function, that's how it works, otherwise parse the $link variable to each function as an argument, or consider an OOP paradigm –  Apr 10 '19 at 03:43

1 Answers1

0

What tim said is correct, one other approach without implementing OOP is using the superglobal $GLOBAL

ex. $GLOBALS['link']

reference: https://www.php.net/manual/en/reserved.variables.globals.php

Michael Peng
  • 806
  • 9
  • 11
  • Though it's not the answer I was looking for but as there are no other option in PHP, i have to go with OOP or $GLOBALS['link'] – b0xed Apr 10 '19 at 03:59