2013-07-23 139 views
0

我知道那不是最好的標題我的問題,但我coulnd't想出一個更好的(建議,歡迎)如何從其他函數文件調用類的函數?

好了,這是我的情況,我有3個文件:

1) classDBConn.php - 在這個文件是我連接到數據庫,並有一些像這樣的功能:

class DBConn{ 
var $conexion; 
private $querySql; 
var $respuesta; 
var $resultado; 
function __construct() { 
    $this->conexion = @mysqli_connect('localhost', 'root', 'pass', 'dataBase'); 
    if(!$this->conexion){ 
     die('error de conexion('.mysqli_connect_errno().')'.mysqli_connect_error());  
    } 
} 
function checkBracketGanador($id_torneo){ 
    $this->querySql = "SELECT COUNT(id_ganador) FROM brackets WHERE id_torneo = '$id_torneo'"; 
    $this->respuesta = mysqli_query($this->conexion,$this->querySql); 
    $this->resultado = mysqli_fetch_array($this->respuesta); 
    return $this->resultado[0]; 
} 
// More functions with queries 

注:查詢和功能都很好

2)inc_conf.php - 在這個文件是我創建會話和對象數據庫康涅狄格州。代碼:

session_start(); 
include('classDBConn.php'); 
$functionsDBConn= new DBConn(); 
$id_usuario = isset($_SESSION["IDUSUARIO"]) ? $_SESSION["IDUSUARIO"] : false; 

3)workingOn.php - 在此文件中,我調用DBConn以便使用這些查詢。如果我做這樣的呼籲僅僅是罰款:

$res = $functionsDBConn->checkBracketGanador($id_torneo); 
echo $res; 

但是,如果我去做了一個函數內部被這裏的一切不順心

function test(){ 
    $res = $functionsDBConn->checkBracketGanador($id_torneo); 
    return $res; 
} 
$a = test(); 
echo $a; 

我不斷收到此錯誤:

致命錯誤:調用成員函數checkBracketGanador()在一個非對象在.../someFolder/workingOn.php在線67

我試過了使公共職能classDBConn但沒有工作

我在做什麼調用函數外的函數和發送結果作爲參數傳遞給其他的功能,但,這是我想避免

任何到底是什麼幫助是欣賞。提前致謝。

回答

1

這是與範圍。

我假設你在同一級別實例$functionsDBConn = new DBConn();之外的功能爲

$a = test(); 

如果是這樣,你有2個選項

一:

function test(){ 
    global $functionsDBConn; 
    $res = $functionsDBConn->checkBracketGanador($id_torneo); 
    return $res; 
} 

$functionsDBConn = new DBConn(); 
$a = test(); 
echo $a; 

二:

function test(&$functionsDBConn){ 
    $res = $functionsDBConn->checkBracketGanador($id_torneo); 
    return $res; 
} 
$functionsDBConn = new DBConn(); 
$a = test($functionsDBConn); 
echo $a; 

基本上,您必須通過告訴test()函數在全局範圍global $functionsDBConn;內可用,或者將其作爲參數傳遞給函數,從而使您實例化的對象在test()函數的範圍內可見。

你也可以使checkBracketGanador()是一個靜態方法,但不要急於複雜。

+0

選項1是贏家,它的魅力。謝謝bro – Mollo

1

在函數中使用global關鍵字。函數內部的變量不會調用其範圍外的值。

function test(){ 
    global $functionsDBConn; 
    $res = $functionsDBConn->checkBracketGanador($id_torneo); 
    return $res; 
} 
+0

感謝您的幫助 – Mollo

相關問題