包含文件变量,全局函数和类之间的PHP范围问题

时间:2014-07-21 13:44:30

标签: php function class variables scope

我在弄清楚为什么类中的函数没有正确地使用全局函数连接到数据库时遇到了问题。它可以正常访问函数,它将建立一个连接字符串,但它连接到错误的数据库,我认为它与范围有关,但不知道如何解决它。

它设置了这样的东西

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类调用另一个函数的函数中时,它对我没有用。

任何人都知道会发生什么事?

1 个答案:

答案 0 :(得分:0)

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 ); 
 }