I think I have a problem in understanding how OOP works. I have already changed the code that it works, but this is not the way that I think. The following scenario (No, I do not create a user login on my own, itβs better for a local developer to understand OOP):
I have a database.php file:
class Database {
private $conn;
private $dsn = 'mysql:dbname=test;host=127.0.0.1';
private $user = 'root';
private $password = '';
public function __construct() {
try {
$this->conn = new PDO($this->dsn, $this->user, $this->password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "";
die();
}
return $this->conn;
}
}
So, in this class, I create a database connection and return a connection (object?)
Then I have a second class, the famous User class (in fact, I do not use autoload, but I know about it):
include "database.php";
class User {
private $conn;
public function __construct() {
$this->conn = new Database();
}
public function login() {
$stmt = $this->conn->prepare("SELECT username, usermail FROM user");
if($stmt->execute()) {
while($rows = $stmt->fetch()) {
$fetch[] = $rows;
}
return $fetch;
}
else {
return false;
}
}
}
, . , . login
. usermails . :
$user = new User();
$list = $user->login();
foreach($list as $test) {
echo $test["username"];
}
. , :
: undefined :: prepare()
, , .
, :
$conn
database.php public, private ( , ...? , , ? ? , , ..)
, , :
$this->conn->prepare
$this->conn->conn->prepare
user.php. , .
, user.php $this->conn = new Database()
, DB, , conn->
, - . , , , , .
!:)