PHP-包含或要求不';在oop中不能在类文件中工作
如果我将常数保持在DB.php,那么一切都正常PHP-包含或要求不';在oop中不能在类文件中工作,php,oop,error-handling,Php,Oop,Error Handling,如果我将常数保持在DB.php,那么一切都正常 <?php include 'config.php'; class DB { private static $pdo; private $table = 'student_info'; public static $name; public static $dep; public static $age; public static function connection(){
<?php
include 'config.php';
class DB {
private static $pdo;
private $table = 'student_info';
public static $name;
public static $dep;
public static $age;
public static function connection(){
try{
self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname='.DB_NAME,DB_USER,DB_PASS);
}catch( PDOException $e ){
echo $e->getMessage();
}
return self::$pdo;
}
public static function prepareOwn($sql){
return self::connection()->prepare($sql);
}
public function readAll(){
$sql = "SELECT * FROM $this->table";
$stmt = self::prepareOwn($sql);
$stmt->execute();
return $stmt->fetchAll();
}
public function setValue($name, $dep, $age){
self::$name = $name;
self::$dep = $dep;
self::$age = $age;
}
public function insertValue(){
$sql = "INSERT INTO $this->table (name, department, age) VALUES (:name, :department, :age)";
$stmt = self::prepareOwn($sql);
$stmt->bindParam(':name', self::$name);
$stmt->bindParam(':department', self::$dep);
$stmt->bindParam(':age', self::$age);
return $stmt->execute();
}
}
?>
但问题是,当我在单独的文件中保持常量时,比如config.php和在DB.php中包含或要求config.php文件,然后我得到注意:当我尝试在index.php页面中使用spl\u autoload\u register()时,使用未定义的常量
我不知道到底是什么问题。为什么它不起作用??我想知道逻辑。看起来您是在使用类的前使用常量。您的
config.php
只有在您尝试使用DB类时才会被包括在内,因此autoloader将包括DB.php
(然后config.php
也将被包括在内).检查此链接:您能否提供用于启动连接的部分代码以便于更好地理解?config.php代码是您确定您使用的是$new=new DB代码>但不是$new=new DB()代码>我正在使用常量建立连接。所以我在DB课之前不使用它