Php 找不到类错误
我很难让我的代码正常工作,在尝试将代码分割成单独的类文件之前,它工作得很好。我收到错误Php 找不到类错误,php,oop,Php,Oop,我很难让我的代码正常工作,在尝试将代码分割成单独的类文件之前,它工作得很好。我收到错误致命错误:在第25行的/var/www/EncoreCMS/test.php中找不到类“UserMethods”。我有一个DatabaseConnections.php文件,其中包含用于建立数据库连接的类和方法。还有一个UserMethods.php文件,它在UserMethods类中存储了retrievePassword()方法。我的代码如下: DatabaseConnections.php: <?ph
致命错误:在第25行的/var/www/EncoreCMS/test.php中找不到类“UserMethods”。我有一个DatabaseConnections.php
文件,其中包含用于建立数据库连接的类和方法。还有一个UserMethods.php
文件,它在UserMethods
类中存储了retrievePassword()
方法。我的代码如下:
DatabaseConnections.php:
<?php
require '/resources/library/DB.php';
class DatabaseConnection
{
private $conn = null;
public function __construct(PDO $conn)
{
$this->conn = $conn;
}
protected function getConnection()
{
return $this->conn;
}
}
?>
UserMethods.php:
<?php
class UserMethods extends DatabaseConnection
{
public function retrievePassword($userName)
{
$stmt = $this->getConnection()->prepare('SELECT `password` FROM `users` WHERE `userName`= :userName');
$stmt->bindValue(':userName', $userName);
$stmt->execute();
$salt = $stmt->fetchColumn();
return $salt;
}
public function retrievePictures($userName)
{
$stmt = $this->getConnection()->prepare('SELECT `userName` FROM `users` WHERE `userName`= :userName');
$stmt ->bindValue(':userName', $userName);
$stmt->execute();
$user = $stmt->fetchColumn();
return $user;
}
}
?>
test.php:
<?php
ini_set('display_errors', true);
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
require "$root/resources/library/DB.php";
function __autoload($class_name)
{
//class directories
$directorys = array(
'Applications/Database/Classes/',
'Applications/User/Classes/'
);
//for each directory
foreach($directorys as $directory)
{
//see if the file exsists
if(file_exists($directory.$class_name . '.php'))
{
require_once($directory.$class_name . '.php');
//only require the class once, so quit after to save effort (if you got more, then name them something else
return;
}
}
}
$userName = "testuser";
$a = new UserMethods($conn);
echo $a->retrievePassword($userName);
?>
我解决了这个问题,请参见更新的代码在哪里加载类文件?我看到了实例化它的尝试,以及自动加载方法,但没有明确说明这个自动加载正在命中UserMethods.php文件。还有,为什么directorys数组中会出现冗余?实际上我刚刚发现我调用了同一个目录两次,我将第二个目录更改为`Applications/User/UserMethods',但现在我又遇到了一些错误,我认为我可以解决Catchable致命错误:参数1传递到DatabaseConnection::\uu construct()必须是PDO的一个实例,没有给定,在第25行的/var/www/EncoreCMS/test.php中调用,在第9行的/var/www/EncoreCMS/Applications/Database/Classes/DatabaseConnection.php中定义,同时违反了LSP
和SRP
@Yamaha32088谷歌坚实的原则