I'm trying to create a class for my database: class structure as below
<?php
require_once("config.php"); // include(Username, passowrd, server and databaseName)
class MySQLDatabase{
private $connection;
function __construct(){
$this->openConnection();
}
public function openConnection(){
$this->$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PWD, DB_NAME);
if(!$connection){
die("Database connection failed: ".mysql_error);
}
}
}
$database = new MySQLDatabase();
$db =&$database;
?>
then my first step was check this weather work or not. so I code index.php file as below
<?php
require("../includes/database.php"); if(isset($database)){
echo "true";
}else{
echo "false";
}
?>
after that I run the program and I got errors as below. I can not understand the reason. I google it and there are no clear solution for this. is there are anyone can help me to understand why this happen and how to solve this?
( ! ) Notice: Undefined variable: connection in C:\\wamp\\www\\waytoits\\includes\\database.php
on line 9
Call Stack
# Time Memory Function Location
1 0.0005 240792 {main}( ) ..\index.php:0
2 0.0008 249872 require( 'C:\wamp\www\waytoits\includes\database.php' ) ..\index.php:3
3 0.0013 250528 MySQLDatabase->__construct( ) ..\database.php:55
4 0.0013 250592 MySQLDatabase->openConnection( ) ..\database.php:15
( ! ) Fatal error: Cannot access empty property in C:\wamp\www\waytoits\includes\database.php on line 9
Call Stack
# Time Memory Function Location
1 0.0005 240792 {main}( ) ..\index.php:0
2 0.0008 249872 require( 'C:\wamp\www\waytoits\includes\database.php' ) ..\index.php:3
3 0.0013 250528 MySQLDatabase->__construct( ) ..\database.php:55
4 0.0013 250592 MySQLDatabase->openConnection( ) ..\database.php:15
You are using $this->$connection
instead of $this->connection
. Remove the $
sign in connection
and try again.
$this::$connection
(with the $
preserved) would refer to a static variable. Because you have a class variable you should access it via $this->connection
Also you need to use the same instructions in your if
-statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.