How to solve the prepare error of this script? [closed]

1

I am 2 hours looking for a solution to this problem ] [1]. I'm starting a Virtual store with PHP course and the error is as follows: it says I'm trying to give prepare strong> to an object not instantiated.

The logic is this: he made the CRUD class and is instantiating it for now, just to illustrate, within the in> ConnDB . Why is this error occurring?

highlight_file in the files so they can see the script and the error.

// autoload - para chamar todas as classes instanciadas
function __autoload($class) { require_once "{$class}.class.php"; }

// final - pode instanciar mas não pode extender
// abstract - pode extender mas não pode instanciar 
abstract class ConnDB
{
    private static $conexao;

    private function setConn()
    {
        is_null(self::$conexao) ? 
                self::$conexao = new PDO("mysql:host=mysql.axitech.com.br;dbname=dbname", "user", "pass") :
                self::$conexao;
    }

    public function getConn()
    {
        return $this->setConn();
    }
}

$inserir = new CRUD;
$inserir->insert('user', 'user=?, email=?, cidade=?', array('yesmarcos', '[email protected]', 'Campo Grande'));
  

Fatal error: Call to a member function prepare () on a non-object in /home/axitech/www/mylojavirtual/require/class/CRUD.class.php on line 11

    
asked by anonymous 20.12.2015 / 01:15

1 answer

1

Well folks, the only problem in that case here is that I was forgetting to return the connection result in setConn and the getConn was in return nothing since the method setConn was also not returning anything. It looks like this:

// autoload - para chamar todas as classes instanciadas
function __autoload($class) { require_once "{$class}.class.php"; }

// final - pode instanciar mas não pode extender
// abstract - pode extender mas não pode instanciar 
abstract class ConnDB
{
    private static $conexao;

    private function setConn()
    {
         return  // <----- O erro era aqui          
         is_null(self::$conexao) ? 
                self::$conexao = new PDO("mysql:host=mysql.axitech.com.br;dbname=dbname", "user", "pass") :
                self::$conexao;
    }

    public function getConn()
    {
        return $this->setConn();
    }
}

$inserir = new CRUD;
$inserir->insert('user', 'user=?, email=?, cidade=?', array('yesmarcos', '[email protected]', 'Campo Grande'));
    
21.12.2015 / 12:49