0

If I keep constant at DB.php Then everything works.

<?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();
    }
}
?>

But the problem is when I keep constant at separate file like config.php and include or require config.php file at DB.php then I get Notice: Use of undefined constant when I try to use spl_autoload_register() at index.php page.

I don't know what is the problem actually. Why it isn't not working?? I want to know the logic.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Sahidul Islam
  • 53
  • 2
  • 10

1 Answers1

0

Looks like you are using your constant before using of your class. Your config.php will be included only when you will try to use DB class - so autoloader will include DB.php (and then config.php will be included too).

Roman S
  • 162
  • 8