Using "global" in php

I'm here in training mode, very new to PHP, so I work with sample code. Please forgive my use of "global" here, but I want to understand the scope of the php variable.

Here is myGlobals.php:

<?php global $db_server; // other code not shown ?> 

Here's connectToDb.php:

 <?php require_once 'myGlobals.php'; // no declared functions in this file, all inline code $db_server = mysql_connect(.....); mysql_select_db( "theDatabase", $db_server); ?> 

Here is addDbRecords.php:

 <?php require_once 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); function doAddDeleteRecord($db_server) { //global $db_server; if( !mysql_query($query, $db_server)) { // handle the error... } } ?> 

Here is index.php:

 <?php require_once 'myGlobals.php'; require_once 'connectToDb.php'; require_once 'addDbRecords.php'; // this is simplified, just trying to show that everything in inline code ?> 

Here is the problem. When I call doAddDeleteRecord($db_server) inside the addDbRecords.php file above, $db_server invalid - it is null - when I call mysql_query(.., $db_server, ...) this error message is:

"Warning: mysql_query () expects parameter 2 - resource, null in C: \ xampp \ htdocs \ addDbRecords.php on line 29"

So, I tried to use the 'global' declaration inside doAddDeleteRecord() (commented above) - no change.
mysql_query(...) still does not work with a NULL value for $db_server .

I know that mysql_connect(....) works because another code retrieves all my records from my database successfully (using SELECT) and the existing records are displayed correctly in the browser.

So, in my opinion, the fact that $db_server declared using "global" should mean that the scope of $db_server is such that after mysql_connect(...) is called - in the file area in all my files, $db_server will be a valid connection to my database.

I am only trying to learn about php scoping , not OOAD or anything else (for now). Why is $db_server() null here?

+4
source share
2 answers

So you have:

 <?php global $db_server; // other code not shown ?> 

and you include this if necessary:

 require_once 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); 

The problem is that if you already included "myGlobals.php" in another place, it will not be included here. Therefore, you cannot guarantee that the global value will be included in the scope.

Instead, write:

 require 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); 

Or use a much better approach:

 // other inline code..... doAddDeleteRecord($GLOBALS['db_server']); 
+5
source

I think there is a problem of hiding the area; that is, you use the same name ($ db_server) for the global and local function variables. The local scope of the function hides the name of the global variable. If you have a global one, you do not need to pass it into your function; if you do, do not use the same name for this.

+1
source

All Articles