I am trying to make a database connection in PHP using two different classes. There is an error in my object creation:
Error: Parse error: syntax error, unexpected '$obj' (T_VARIABLE), expecting function (T_FUNCTION)
The error occurs on this line: $obj = new UserController();
This is my Connection
class:
class Connection
{
public $servername = "localhost";
public $username = "root";
public $password = "";
public $dbname = "web-portal";
function database (){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return $conn;
} else {
return $conn;
}
}
}
This is my UserController
class:
class UserController extends Connection {
$obj = new UserController();
//$obj->database();
function getUser ($userId) {
// Sql query to select record from user table
$sql = "SELECT * FROM User where user_id = ".$userId;
//Excute sql query
$result = $conn->query($sql);
//If record exists
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$conn->close();
return $row;
} else {
//If no record exists return row 0
$row = 0;
return $row;
}
}
}