2016-03-04 78 views
0

我正在使用一些php代碼,我嘗試訪問一個類/公共函數,這樣我就可以在數據庫連接的情況下執行一個if/else函數。我之前只使用過另一個php文件(dirname(FILE),但我不知道該如何調整該代碼以立即到達類/公共函數,因爲它們位於相同的「頁面」/ php文件中。在PHP中,我怎樣才能達到我的課程/公共職能?

class ConnectionInfo 
{ 

    public function GetConnection() 
    { 

    $this->conn = mysqli_connect("localhost", "user","pass", "db") or die(mysqli_error($mysql_pekare)); 

    } 
} 


$connectionInfo = new ConnectionInfo(); 
$connectionInfo->GetConnection(); 

if (!$connectionInfo->conn) 
{ 
    //Connection failed 

} 

else 
{ 
    //Connection succeded 
} 

回答

1

一種方法是把這些變量從$conn公共ConnectionInfo和你的對象以後使用它:

class ConnectionInfo { 
    public var $conn = null;  
    public function GetConnection() { 
     $this->conn = mysqli_connect("localhost", "user","pass", "db") or die(mysqli_error($mysql_pekare)); 
    } 
} 

及更高版本:

if (!$connectionInfo->conn) { 
    //Connection failed 
} 

另一個是return函數值GetConnection()

+0

謝謝!那樣做了。 –

+0

@ William.John:很高興能有任何幫助。 – Jan

+0

該方法是否安全並且不受SQL注入的影響?或者,如果你使用表單,這只是一件事情? –