PHP/mysqli undefined variable/empty property error -
i keep getting error "undefined variable: conn" , "cannot access empty property" when trying return database object $conn. database connection working, however. there better way return database object $this->$conn;?
class database { private $host = "xxxx"; private $database = "xxxx"; private $user = "xxxx"; private $password = "xxxx"; public $conn = ""; function db_connect() { try { $conn = mysqli_connect($host,$user,$password,$database); $conn; echo "connected database"; echo "<br>"; return $conn; } catch(pdoexception $e) { echo 'connection failed:'; echo "<br>"; echo $e->getmessage(); } } public function __construct(){ $this->db_connect(); return $this->$conn; }
the line:
$conn = mysqli_connect($host,$user,$password,$database);
should be:
$this->conn = mysqli_connect($host,$user,$password,$database);
you should remove line:
return $this->$conn;
first of all, constructors shouldn't return (php automatically returns new object). second, should $this->conn
(with no $
before conn
).
finally, line:
$conn;
is both wrong , serves no purpose. rid of it.
Comments
Post a Comment