Good afternoon, I made a request, it works fine, but PHPstorm emphasizes that the db_connection function 'Missing return statement'

class DB { protected $connection_db_link; public $db_users = 'root'; public $db_host = 'localhost'; public $db_name = 'gallery_images'; public $db_pass = 'root'; function db_connection(){ try{ $this->connection_db_link = new PDO("mysql:host=$this->db_host;$this->db_name",$this->db_users,$this->db_pass); $this->connection_db_link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection_db_link; }catch (PDOException $e){ echo $e->getMessage(); } } // function display_connection(){ // if($this->connetction_db_link == true){ // echo 'connection success'; // } // } } 

Question: How to do right ???

    2 answers 2

    rightly done like this

     function db_connection(){ $this->conn = new PDO("mysql:host=$this->db_host;$this->db_name",$this->db_users,$this->db_pass); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->conn; } 

    Catching an exception only in order to display it is an embarrassment bordering on sabotage.

      In the case of an exception, nothing is returned. Add return Null; in the catch or just before the end of the function.