0

I know thats not the best title for my question but I coulnd't come up with a better one (Suggestions are welcome)

Well, this is my situation, I have 3 files:

1) classDBConn.php - In this file is where I connect to the DB and have some functions like this:

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

Note: queries and functions are fine

2)inc_conf.php - In this file is where I create the session and object DBConn. Code:

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

3) workingOn.php - In this file is where I make calls to DBConn in order to use those queries. If I do a call like this is just fine:

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

But, if I do it inside a function is where everything goes wrong

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

I keep getting this error:

Fatal error: Call to a member function checkBracketGanador() on a non-object in .../someFolder/workingOn.php on line 67

I've tried making public functions in classDBConn but didn't work

What I'm doing is calling the function outside the function and sending the result as a parameter to the other function but thats exactly what I want to avoid

Any help is appreciate. Thanks in advance.

4

2 回答 2

1

在函数内使用global关键字。函数内部的变量不会调用其范围之外的值。

function test(){
    global $functionsDBConn;
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
于 2013-07-23T22:32:26.813 回答
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() 成为静态方法,但不要急于复杂化。

于 2013-07-23T22:30:06.183 回答