【问题标题】:PHP Scope Issue Between Included File Variable, Global Function, And Classes包含的文件变量、全局函数和类之间的 PHP 范围问题
【发布时间】:2014-07-21 13:44:29
【问题描述】:

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

它是这样设置的

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 调用另一个的函数中时,它对我来说不起作用。

有人知道会发生什么吗?

【问题讨论】:

  • 我确实知道,但我在工作的地方没有太多选择:\ 我想重写大量代码,但我没有时间/能力,因为它会破坏多少。但希望在不久的将来我可以,就目前而言,我需要让一些东西正常工作。然后我可以和我的老板谈谈重写的事情,找出所有使用代码的人,这样他们就可以修改他们的代码。您也应该在这里看到我们的数据库是如何设置的,有一些……不好的编码习惯。

标签: php function class variables scope


【解决方案1】:
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 ); 
 } 
}

可以在这里使用可选的数据库

什么时候

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多