Problem when inheriting PDO class in class Conexion

0

Greetings, I raise my problem. Create a class called Connection in which I have the constructor method that will contain my connection. I have two problems:

1- When creating the Connection class in this way:

<?php

class Conexion{
    private $con;

    public function __construct(){

        try{
            $this->con = new PDO('mysql:host=localhost;dbname=poo_pdo','root','');

        }catch(PDOExcepcion $e){
            echo $e->getMessage();
            exit;
        }
    }

    //Metodo para llamar la conexion y decirle que se va a ejecutar una query
    public function consultaSimple($sql){
        $this->con->prepare($sql); 
    }

    //Metodo para retornar lo que se consulte
    public function consultaRetorno($sql){
        $datos= $this->con->prepare($sql);
        $datos->execute();
        return $datos;
    }
}
?>

This connects well without problems, but when I execute methods like for example a method that contains a query according to id throws me an error, which tells me that the method prepare () or execute () or any of the methods belonging to PDO tells me that the method is not defined in the class Connection, I have been looking for and according to what I have seen is because I must inherit the class PDO in my class connection, but I do not know if this is the only solution to the problem, I have tried it in the way that I mention inheriting the PDO class and it works without problems. But now I have the following concern when I inherited the PDO class in my connection class, staying like this:

<?php 

class Conexion extends PDO {

   private $type = 'mysql';
   private $host = 'localhost';
   private $db = 'ojeda';
   private $user = 'root';
   private $pass = ''; 

   public function __construct() {
      //Sobreescribo el método constructor de la clase PDO.
      try{

         parent::__construct($this->type.':host='.$this-
      >host.';dbname='.$this->db, $this->user, $this->pass);

      }catch(PDOException $e){
         echo $e->getMessage();
         exit;
      }
   } 
} 
?>

Having it this way works also, but then at the time of using namespace before my class Connection and when loading the autoload it throws me an error which tells me that the PDO class does not exist, I do not understand at all because it tells me that. The namespace places them with the same name as the folder that contains the file. But I really do not know why this happens. If someone can clarify the doubt I appreciate it.

    
asked by Alejo Mendoza 27.12.2017 в 04:03
source

0 answers