I have been experimenting with persistent data from a class construct, I am trying to make a persistent connection through my public __construct, so I can use my database connection information throughout my class. My code is as followed:
class Inbox {
# private $Database;
public function __construct() {
$this->$Database = new mysqli ('localhost','root','xxx','test');
}
public static function TestConnect (){
if (self::Database){
echo "Success When Connecting To Database";
}else{
echo "Problems When Connecting To Database";
}
}
public static function TestSelect(){
$Select = $this->Database->prepare("SELECT * FROM test");
$Select->execute();
$Select->bind_result($Test_ID, $Test_UName);
$Select->fetch();
print_r($Select);
}
}
$Foo = new Inbox();
$Foo->TestSelect();
Now. When running
I am presented with the following errors:
Notice: Undefined variable: Database in C:\xampp\htdocs\InboxFeature\Api\Class.php on line 15
Fatal error: Cannot access empty property in C:\xampp\htdocs\InboxFeature\Api\Class.php on line 15
I change my lines to:
$Select = self::Database->prepare("SELECT * FROM test");
and uncomment:
private $Database;
I get presented with the error:
Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in C:\xampp\htdocs\InboxFeature\Api\Class.php on line 25
So my overall question, is where exactly have I gone wrong, I have looked at examples shown on Stackoverflow with using the __construct()
method. I can't see where it's gone wrong for me.
Using the Answer provided. I appended the following changes:
private static $Database;
public function __construct() {
self::$Database = new mysqli ('localhost','root','xxx','test');
}
public static function TestSelect(){
$Select = self::$Database->prepare("SELECT * FROM test");
$Select->execute();
$Select->bind_result($Test_ID, $Test_UName);
$Select->fetch();
echo $Test_ID;
}
This has successfully worked. Thank you for the quick response