Use global variables in a class

前端 未结 4 1721
日久生厌
日久生厌 2020-11-22 13:36

I\'m trying to create a pagination class and use a variable from outside the class.

But it\'s giving me the fatal error \"Call to a member function query() on a non-

4条回答
  •  遇见更好的自我
    2020-11-22 13:51

    Although I do agree that the dependency model is nice, for the database, I personally use a static connection that is available to all instances of the database class and the create instances to query whenever I need one. Here is an example:

    lastQuery = $query;
            $this->result = mysqli_query(self::$_conn, $query);
            //process result, return expected output.
        }
    }
    
    //create connection to the database, this connection will be used in all instances of DB class
    DB::connect('local', 'DB_USER', 'DB_PASS');
    
    //create instance to query
    $test = new DB;
    //do query
    $test->query("SELECT * FROM TABLE");
    
    //test function
    function foo(){
        //create instance to use in this function
        $bar = new DB;
        //do query
        $bar->query("SELECT * FROM OTHER_TABLE");
        //return results
        return $bar->fetchArray();
    }
    

    That way I can create all the instances I want of DB within any function, method...etc and use that local instance of the class to do all my queries. All instances use the same connection.

    One thing to note though is that this only allows for one connection to the database per defined class but I only use one so this isn't an issue for me.

提交回复
热议问题