简体   繁体   中英

PHP global $db call in function

I have the following code:

function beginProcess(){
    global $db; 
    $sql = "SELECT last_batch from ".TABLE_STATUS.";";            
    $lastBatch = $db->Execute($sql);
    $lastBatch=(int)$lastBatch->fields['last_batch'];
    echo "<BR/>Last Batch = ".$lastBatch;

    if ($lastBatch >=1 && $lastBatch <=3 ){
        $batch = $lastBatch +1;
    }else{
        $batch = 1;
    }
        processBatch($batch);
}

Will $db be available to the processBatch function so I can use db functionality or do I have to define it again in processBatch() ?

No, it will not be. You won't be able to access $db inside the processBatch() function because it is outside the scope of the function -- that means PHP can only see the variables defined inside the function. You could use the global keyword (as you're currently doing with the beginProcess() function) to let PHP know that the variable is outside the function's scope -- and instruct it to import the variable into the function scope.

It's generally considered bad practice to use global variables in your code, and I think a better course of action would be to pass the $db into the function as a function parameter:

function processBatch($db, $batch){
    // $db is now available inside the function
    // more code ...
}

That way, your code will be cleaner and more maintainable. Consult the PHP manual for more information on variable scope.

Yes you have to use global keyword in progressBatch function like,

function processBatch($batch){
   global $db;
   // your remaining code
}

Read Variables Scope

Alternatively you have to pass $db in processBatch function like,

function processBatch($batch,$db){
   // $db available now
   // your remaining code
}

And Call it like,

processBatch($batch,$db);

You need to redefine it in every function that uses it: http://php.net/manual/en/language.variables.scope.php

If you don't want that, you can use

$GLOBALS['db']

instead of

global $db;
$db

which is identical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM