包括文件变量,全局函数和类之间的PHP作用域问题


PHP Scope Issue Between Included File Variable, Global Function, And Classes

我有一个问题,弄清楚为什么一个类内的函数不能正确使用全局函数连接到数据库。它可以访问函数很好,它将建立一个连接字符串,但它连接到错误的数据库,我认为它与范围有关,但不确定如何补救。

它是这样设置的

include "variableScript.php"; //contains variable set by another script
//other code
function connectDB(){
   global $scriptVar;
   $db;
   if(strcmp($scriptVar, 'DB1') == 0){
      $db = 'DB1';
   }
   else{
      $db = 'DB2';
   }
   //DB connection code here, user/pass come elsewhere.
}
//other code
class A{ //this class is called elsewhere
   // class variables here, one being a database connector
   // class constructor
   public function run(){
      $this->dbConn = connectDB();
      //other code in run function
   }
   // other class function
}

现在,我肯定知道$scriptVar设置正确,数据库选择是正确的,当它是使用connectDB函数的另一个脚本的功能(不在类中),所以我认为它必须处理范围和类。正如我所说,我认为这是一个范围问题。当全局函数从类内部调用时,我认为它不知道$scriptVar是什么。我不确定它是否试图在类或其他地方找到$scriptVar。当我尝试将全局$scriptVar放入类A的函数中调用另一个时,它没有为我工作。

有谁知道发生了什么事吗?

function connectDB(){
   global $scriptVar;
   $db="";
   if(strcmp($scriptVar, 'DB1') == 0){
      $db = 'DB1';
   }
   else{
      $db = 'DB2';
   }
   //DB connection code here, user/pass come elsewhere.
}

我想它会对你有帮助,如果它不能工作,你可以使用这个代码

class R_DB
{   
    public $host     = "localhost";
    public $database = "dbname"; 
    public $username = "root"; 
    public $password = ""; 
    public $conId    = 0;  
    public $row;          
 //call connection method upon constructing 
 public function __construct(){
  $this->dbConnect(); 
 }
 //connection to the database
 public function dbConnect() 
    { 
        if( 0 == $this->conId ) 
            $this->conId=mysql_connect( $this->host, $this->username, $this->password ); 
        if( !$this->conId ) 
   $this->stopExec( "Trying to connect.... Result: failed" ); 
        if( !mysql_query( sprintf( "use %s", $this->database ), $this->conId ) ) 
            $this->stopExec( "cannot use database ".$this->database ); 
 } 
}

可以在这里使用

使用可选db时

public function dbConnect($host, $dbuser, $dbpass, $dbname) 
    { 
        if( 0 == $this->conId ) 
            $this->conId=mysqli_connect( $dbhost, $dbuser, $dbpass, $dbname ); 
        if( !$this->conId ) 
   $this->stopExec( "Trying to connect.... Result: failed" ); 
        if( !mysql_query( sprintf( "use %s", $dbname ), $this->conId ) ) 
            $this->stopExec( "cannot use database ".$this->database ); 
 }