Reputation: 1690
I am new to this subject.I am just trying to connect my db and fetch data. When working with static connection it is working but working with nonstatic not.As I said I don't know much about Php, probably missing something easy. Error when trying to get nonstatic The page cannot be displayed because an internal server error has occurred. My code
> <?php
class DB_Connect extends mysqli{
// protected static $connection;//working
protected $connection; / not working
function __construct() {
}
function __destruct() {
}
public function connect() {
if(!isset($this->$connection)) {
$config = parse_ini_file('./configOop.ini');
$this->$connection = new mysqli($config['dbhost'],$config['username'],$config['password'],$config['dbname']);
}
else{}
return $this->$connection;
/*
// using this part for static connection object, working
if(!isset(self::$connection)) {
$config = parse_ini_file('./configOop.ini');
self::$connection = new mysqli($config['dbhost'],$config['username'],$config['password'],$config['dbname']);
}
else{}
return self::$connection;
*/
}
// Closing database connection
public function close() {
// mysql_close();
}
}
?>
//
<?php include 'db_connectOop.php'; ?>
<?php
// error_reporting(0);
$db=new DB_Connect();
$dbConn=$db->connect();
if($result =$dbConn->query("Select * from cities")or die($dbConn->error)){
if($count=$result->num_rows){
while($row = $result->fetch_object())
{
echo $row->idcities;
}
}
}
?>
Upvotes: 3
Views: 873
Reputation: 116110
A tiny mistake: $this->$connection
should be $this->connection
.
PHP doesn't need the second $
, since it already knows (because of the ->
) that you are referring to a property. If you would add that $
like you did, you are basically getting the value of the local variable $connection
, and using that value as the property name.
Upvotes: 5