我是OOP PHP的新手,遇到了奇怪的情况,一切正常,但这只是事实,我不明白为什么。
到目前为止,我被告知,只要方法是静态的,就可以使用它们而无需实例化对象。因此,我在User类中创建了一些方法,而没有声明它们是静态的,但是它们仍然可以工作并且表现为静态。
这是我的数据库课程:
class Database {
private function connect() {
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($connection->connect_errno) {
die("Database failed.". mysqli_error());
}
return $connection;
}
protected function query($sql) {
//$result = mysqli_query($this->connect(), $sql);
$result = User::connect()->query($sql);
return $result;
}
}
这是我的User类,其中包含所有未设置为静态的方法:
class User extends Database {
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function findAllUsers() {
return self::findThisQuery("SELECT * FROM users");
}
public function findUserById($id) {
$result = self::findThisQuery("SELECT * FROM users WHERE id = {$id} LIMIT 1");
$res = $result->fetch_assoc();
return $res;
}
public function findThisQuery($sql) {
$result = User::query($sql);
return $result;
}
public function instantiation($found_user) {
$user = new self;
$user->id = $found_user['id'];
$user->username = $found_user['username'];
$user->password = $found_user['password'];
$user->first_name = $found_user['first_name'];
$user->last_name = $found_user['last_name'];
return $user;
}
}
然后,每当我这样称呼他们时,都这样:$found_user = User::findUserById(2);
。有人可以解释我为什么吗?