0

learning php for some time, maybe I miss some fundamental concept about this-> and selft::, but here is my example:

Firts, I have this :

class DB {
  private static function getDBConnection() {
    $dbconfig = parse_ini_file(ROOT_DIR."\include\config.ini");
    $serverName = $dbconfig["sqlserver"];
    $connectionInfo = ["Database"=>$dbconfig["database"],"UID"=>$dbconfig["dbuser"],"PWD"=>$dbconfig["password"]];
    $conn = sqlsrv_connect($serverName,$connectionInfo);
    if ($conn === false) {  
        echo "Could not connect.\n";  
        die(print_r(sqlsrv_errors(), true));  
    }  
    return $conn;
  }

Then I have this, but when executing the sqlsrv_fetch_array later throws an error:

public static function queryDB($query, $params = array()) {
    try{
        if ($stmt = sqlsrv_query(self::getDBConnection(), $query, $params)) {
            echo "Statement completed.\n";  
        } else {  
            echo "Statement could not be completed.\n";  
            die(print_r(sqlsrv_errors(), true));  
        }  
        $data=sqlsrv_fetch_array($stmt);
        return $data;
    }
    catch(Exception $ex){
        echo "Statement could not be executed.\n $ex->getMesssage()";  
        die(print_r(sqlsrv_errors(), true));  
   }
   finally{
        /* Free the statement and connection resources. */  
        sqlsrv_free_stmt($stmt);  
        sqlsrv_close($conn);  
   }
  }

However, this works fine adding $conn = self::getDBConnection(); :

public static function queryDB($query, $params = array()) {
    $conn = self::getDBConnection();
    try{
        if ($stmt = sqlsrv_query($conn, $query, $params)) {
            echo "Statement completed.\n";  
        } else {  
            echo "Statement could not be completed.\n";  
            die(print_r(sqlsrv_errors(), true));  
        }  
        $data=sqlsrv_fetch_array($stmt);
        return $data;
    }
    catch(Exception $ex){
        echo "Statement could not be executed.\n $ex->getMesssage()";  
        die(print_r(sqlsrv_errors(), true));  
   }
   finally{
        /* Free the statement and connection resources. */  
        sqlsrv_free_stmt($stmt);  
        sqlsrv_close($conn);  
   }
  }

My question is why I have to set it to a local variable and not just use it inside the sqlsrv_fetch_array call ? It may be simple but I want to learn WHY . Thanks !!

Ruben D. Lopez
  • 379
  • 2
  • 9
  • this may be related : https://stackoverflow.com/questions/11710099/what-is-the-difference-between-selfbar-and-staticbar-in-php – YvesLeBorg Jul 15 '20 at 01:35
  • It looks like you are trying to use a singleton class - this may help - https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php – user2182349 Jul 15 '20 at 01:39

0 Answers0