我不断收到此错误,我也不知道为什么:
严重错误:未捕获的错误:找不到类'db' C:\ xampp \ htdocs \ Login-system-oop \ commands.php:2堆栈跟踪:#0 C:\ xampp \ htdocs \ Login-system-oop \ index.php(9):include()#1 {main} 在第2行的C:\ xampp \ htdocs \ Login-system-oop \ commands.php中抛出
我的代码: db.php
<?php
class db {
private $server;
private $usern;
private $pass;
private $database;
protected function connect() {
$this->server = "localhost";
$this->usern = "root";
$this->pass = "";
$this->database = "logsysdboop";
$conn = new mysqli($this->server, $this->usern, $this->pass, $this->database);
return $conn;
}
}
?>
commands.php
<?php
class commands extends db {
public function display() {
$sql = "Select * from users";
$result = $this->connect()->query($sql);
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
foreach ($datas as $data) {
echo $data['user']."<br>";
}
}
}
?>
index.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
include 'commands.php';
$obj = new commands;
$obj->display();
?>
</body>
</html>
答案 0 :(得分:0)
正如 Nigel Ren 所建议的那样,您需要使用以下一种方法将类导入PHP脚本的顶部:
require_once __DIR__ . '/db.php';
require __DIR__ . '/db.php';
include_once __DIR__ . '/db.php';
include __DIR__ . '/db.php';
use db;
而且,一旦固定,将$datas
更改为$data
(因为$datas
似乎是一个错字,并且从未定义),就像下面的commands.php
文件中一样:
<?php
require __DIR__ . '/db.php';
class commands extends db {
public function display() {
$sql = "Select * from users";
$result = $this->connect()->query($sql);
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
foreach ($data as $entery) {
echo $entery['user']."<br>";
}
}
}
?>
答案 1 :(得分:0)
只需使用 require_once(“ db.php”); 在commands.php中 在扩展db类之前。进一步,您将数据存储到$ data数组中,并尝试在循环中从$ datas中检索数据,该循环再次未定义。
更正以上内容,我认为您的代码会没事的。