简体   繁体   English

PHP全局$ db调用函数

[英]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() ? $ db是否可用于processBatch函数,因此我可以使用db功能,还是必须在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. 您将无法在processBatch()函数内访问$db ,因为它不在函数范围之内-这意味着PHP仅可以查看在函数内部定义的变量。 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. 可以使用global关键字(就像您当前对beginProcess()函数所做的beginProcess() )来使PHP知道该变量超出了函数范围-并指示其将变量导入到函数范围内。

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: 通常在代码中使用global变量被认为是不好的做法,我认为更好的做法是将$db作为函数参数传递给函数:

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. 有关变量范围的更多信息,请查阅PHP手册

Yes you have to use global keyword in progressBatch function like, 是的,您必须在progressBatch function使用global keyword ,例如,

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

Read Variables Scope 读取变量范围

Alternatively you have to pass $db in processBatch function like, 或者,您必须在processBatch function传递$db ,例如,

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 您需要在使用它的每个函数中重新定义它: 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. 这是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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