function reference in php

Asked

Viewed 35 times

0

I’m having a problem I can’t reference a method that’s within the class:

Follow the code:

define("LOGIN","root");
define("PWD","");
//define("DB", "pj_fatec");
define("DB", "virtual");
define("SERVER","localhost");

class Conexao {

     public static $conn; 

     public function open() {               
           self::$conn = new mysqli(SERVER, LOGIN, PWD, DB);

           // Check connection
           if (self::$conn->connect_error) {
                die("Connection failed: " . self::$conn->connect_error);
           } 

     }
     static function getconexao(){
         if(self::$conn){
             return self::$conn;                    
         }else{
             $this->open();
             return self::$conn;            
        }                
     }      
 }
  • It’s probably because you’re referencing an object $this within a static function, which can be directly accessed by the class.

  • the problem is to use the open() method without this and with the problems.

  • In this case you have to change the function open() to Static and call self::open() in the second function.

1 answer

0


Hello the static method must set the static property to make it visible, try so:

define("LOGIN","root");
define("PWD","");
//define("DB", "pj_fatec");
define("DB", "virtual");
define("SERVER","localhost");

class Conexao {

    public static $conn = null;

    static function getconexao(){
        self::$conn = (self::$conn===null ? new mysqli(SERVER, LOGIN, PWD, DB):self::$conn);
        if (!self::$conn) {
            die("Connection failed: " . var_dump(self::$conn));
        }
        return self::$conn;                         
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.