PHP function scope

I have a file that drives my reusable functions into a single file ( functions.php ). This is include_once() 'd on every page he needs. I get an error when my user functions try to access a MySQL connection outside their own scope. The source is a bit like this:

 <?php // functions.php $connect = mysql_connect("localhost", "user", "pass") or die("MySQL said: ".mysql_error()); mysql_select_db("database", $connect) or die("MySQL said: ".mysql_error()); // no error /* ... */ function getmotd($user) { $query = "SELECT cid FROM `users` WHERE id = ".$user; $query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource /* ... */ } ?> 

Why can't my function access variables declared above? I can get a successful connection by playing the $connect declaration inside the function.

Any insight on how I can get around this or what am I doing wrong here?

+4
source share
2 answers

Use the global .

Example

 function getmotd($user) { global $connect; $query = "SELECT cid FROM `users` WHERE id = ".$user; $query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource /* ... */ } 

You can also do it as follows

 function getmotd($user) { $query = "SELECT cid FROM `users` WHERE id = ".$user; $query = mysql_query($query, $GLOBALS['connect']); // error occurs here, $connect is not a valid MySQL link-resource /* ... */ } 

If you want to make reusable codes, you will probably be better off with OOP. Create a class for the database and add some properties for the database information and access them from functions using the this .

+6
source

You cannot access $ connect because it is outside the scope of the function; that is, PHP can only see variables inside a function when it is inside it. You can use the global keyword to let PHP know that the variable is outside the scope, as Kemal suggests, but I think the best way is to pass the connection to the function. This will give you better encapsulation. If you learn to write your functions (and later classes) with the transfer of necessary resources and data (a practice known as โ€œdependency injectionโ€), you will find that you have a cleaner and more convenient code. Here is an example:

 function getmotd($db, $user) { $query = "SELECT cid FROM users WHERE id = " . (int)$user; $result = mysql_query($query, $db); /.../ } $connect = mysql_connect(...); mysql_select_db(...); $motd = getmotd($connect, $user); 

Hope this helps.

+5
source

Source: https://habr.com/ru/post/1214846/


All Articles