Scope error - Call to a member function prepare() on a non-object

前端 未结 2 1332
無奈伤痛
無奈伤痛 2020-12-22 09:39

So the scenario is simple. I use class that does something in database but in that class I call another class that also does something in DB.

Thanks, include_once ch

2条回答
  •  旧巷少年郎
    2020-12-22 10:09

    The scope of $DB isn't within the classes because you haven't passed it into the classes. At the moment its just floating around in global scope, but not within the scope of your classes.

    You need to add $DB into the Log class, you can do this as a static variable like so inside your db_config.php

    Log::$DB = $DB;
    

    And use like this in your class

    class Log
    {
        public static $DB;
    
        public static function Add($action)
        {
            try
            {
                include_once "db_config.php";
    
                $ip = $_SERVER['REMOTE_ADDR'];
    
                $time = date('Y-m-d');
    
                $values = array($ip, $action, $time);
                $STH = self::$DBH->prepare("INSERT INTO log (ip, action, time)
                                      VALUES (?, ?, ?)");
    
                $STH->execute($values);
    
                self::$DBH = null;
                $STH = null;
            }
            catch (PDOException $e)
            {
                echo $e->getMessage();
            }
        }
    }
    

提交回复
热议问题