致命错误:未捕获的错误:调用成员函数get()为null

问题描述 投票:0回答:1

我试图通过数据库查询来创建登录/注册系统。我是Php OOP的新手。我有带有代码的类DB.php

class DB{
   protected static $instance = null;
   private $_pdo, 
   $_query, 
   $_error = false, 
   $_results, 
   $_count = 0;

   private function __construct(){
       try{
           $this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
           echo 'Connected';
       } catch(PDOException $e){
           die($e->getMessage());
       }
   }

   public static function getInstance(){
       if(!isset(self::$instance)){
           self::$instance;
       }
       return self::$instance;
   }

   public function query($sql, $params=array()){
         $this->_error = false;
         if($this->_query= $this->_pdo->prepare($sql)){
             if(count($params)){
                 foreach($params as $param){
                     $this->_query->bindValue($x, $param);
                     $x++;
                 }
             }
             if($this->_query->execute()){
                $this->_results=$this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count= $this->_query->RowCount();
             } else{
                 $this->_error = true;
             }
         }
         return $this;
   }

 private function action($action, $table, $where = array()) {
       if(count($where) === 3) {
           $operators = array('=','>','<','>=','<=');

           $field = $where[0];
           $operator = $where[1];
           $value = $where[2];

           if(in_array($operator, $operators)){
               $sql = "{$action} FROM {$table} WHERE {$field}{$operator}?";
               if(!$this->query($sql, array($value))->error()){
                   return $this;
               }
           }
       }
       return false;
 }
 public function get(){
      return $this->action('SELECT *', $table, $where);
 }  
 public function delete($table, $where){
   return $this->action('DELETE', $table, $where);
 }
   public function error(){
       return $this->_error;
   }
}
?>

和index.php之类的>>

<?php
require_once('core/init.php');

$user = DB::getInstance()->get('users', array('username','-','alex'));

if($user->error()){
    echo 'No user';
} else {
    echo 'OK!';
}
?>

并且我遇到致命错误:未捕获的错误:在C:\ xampp \ htdocs \ RegisterSystem \ index.php:4中调用null的成员函数get()堆栈跟踪:#0 {main}在C:\中抛出第4行上的xampp \ htdocs \ RegisterSystem \ index.php有人可以帮我吗?

我试图通过数据库查询来创建登录/注册系统。我是Php OOP的新手。我有DB.php类和代码类DB {protected static $ instance = null;私人$ _pdo,$ ...

function get member
1个回答
0
投票

因为您不是在实例本身上调用get(),而是在该实例的属性上调用。您需要从getInstance()方法返回对象实例。像这样的东西:

© www.soinside.com 2019 - 2024. All rights reserved.