Error using PDO and Autoload

Asked

Viewed 100 times

0

I’m having a problem making a PDO call inside a file that works with an autoload, I believe autoload tries to load everything , even the PDO.

 <?php
 function load($namespace)
 {       
    $namespace=str_replace("\\","/",$namespace);
    $caminhoAbsoluto=__DIR__."/".$namespace.".php";
    return include $caminhoAbsoluto;
 }

spl_autoload_register(__NAMESPACE__."\load");
 ?>

File code where I try to use PDO.

<?php
 namespace Model\login;
 class validar{
 public function teste(){
  $this->buscar();
  }

public function buscar(){
$query="SELECT*from usuario where senha=36398020";
    $con=new PDO('mysql:host=localhost;dbname=login','root','36398020');
    $rest=$con->query($query);
    $rest->fetchAll();
    return $rest;
    }
  }

  ?>

The nevegador returns this warning to me: Warning: include(C: wamp64 www Agenda/Model/login/PDO.php): failed to open stream: No such file or directory in C: wamp64 www Agenda autoload.php on line 5

  • I believe that the $caminhoAbsoluto=__DIR__."/".$namespace.".php"; simply does not work because the PDO is not in this way, so your autoloader should be adapted to load it directly from the DLL or else ignore it and let the PHP handle the class request alone. I think it would be important for you to inform which version of PHP this is happening.

1 answer

4


It has nothing to do with autoload, but the fact that you are trying to use a PDO in namespace Model\login

When does namespace Model\login; one new qualquercoisa will be considered as Model\login\qualquercoisa.

As a consequence, his autoload is invoked, and tries to load the file in that path (hence the file error not found).

Solution:

or you put this at the beginning of the code:

use PDO;

Or call in the root namespace:

$con=new \PDO( ...
//       ^-- note a barra

thus eliminating the ambiguity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.