0

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() ?

asked Nov 18, 2013 at 11:37

3 Answers 3

5

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.

answered Nov 18, 2013 at 11:39
Sign up to request clarification or add additional context in comments.

Comments

1

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);
answered Nov 18, 2013 at 11:39

Comments

1

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.

BenMorel
37k52 gold badges208 silver badges339 bronze badges
answered Nov 18, 2013 at 11:38

2 Comments

I hate downvotes without explanation. Such cowardice!
I countered the downvote, as I see no reason that your answer should have received it. The other answers are expressed more clearly, but yours is factually correct also.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.