Problems with PDO parameter passing

0

I'm studying a book in which I have to do some queries through a TableDataGateway pattern design but I'm getting the following error message:

  

Fatal error: Uncaught Error: Class 'classes \ tgd \ PDO' not found in C: \ xampp   \ htdocs \ libro_php_poo_12_persistence \ classes \ tgd \ Connect.php: 12   Stack trace:

     

0 C: \ xampp \ htdocs \ libro_php_poo_12_persistence   \ example_table_data_gateway2.php (24): classes \ tgd \ Connect-> constructor ()

     

1 {main}   thrown in C: \ xampp \ htdocs \ libro_php_poo_12_persistence \ classes   \ tgd \ Connect.php on line 12

index

product

    <?php
namespace classes\tgd;
class Produto {
    private static $conn;
    private $data;

    public static function setConnection(PDO $conn){

        self::$conn = $conn; 
        ProdutoGateway::setConnection(self::$conn);

    }
    function __get($prop) {
        return $this->data[$prop];
    }
//...
}

TableDataGateway

namespace classes\tgd;

class ProdutoGateway {

    private static $conn;

    public function setConnection(PDO $conn){
        self::$conn = $conn;
    }
    //fazendo buscar por id
    public function find($id,$class = 'stdClass'){
        $sql = "SELECT * FROM produto WHERE id=:id";
        print "$sql<br>\n";
        $result = self::$conn->prepare($sql);
        $result->bindValue(":id",$id,PDO::PARAM_INT);
        $result->execute();
        return $result->fetchObject($class);
    }

    //...
}

Connection

<?php
namespace classes\tgd;


class Connect {
    private static $conn;
    const CONN = array('HOST'=>'xxx','USER'=>'xxx','PASS'=>xxx,'DATA'=>'xxx');

    public function __construct(){
        self::$conn = new \PDO("mysql:host=".self::CONN['HOST'].";"
        . "dbname=".self::CONN['DATA'],self::CONN['USER'],self::CONN['PASS']);
        $conn = self::$conn;
        $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        return Produto::setConnection($conn);
    }
}
    
asked by anonymous 25.10.2017 / 22:31

1 answer

3

When you reference a class within a namespace without identifying it with the use statement, PHP will understand that this class will also belong to the namespace . This is by doing:

<?php

namespace classes\tgd;

class Foo {
    public function method(PDO $pdo) {}
}

PHP will understand that the PDO class belongs to the namespace classes\tgd . To resolve this, whenever you use the class inside a namespace , you need to identify its source. Since the PDO belongs to the global context, just put:

use PDO;

Getting something similar to:

<?php

namespace classes\tgd;

use PDO;

class Foo {
    public function method(PDO $pdo) {}
}
    
26.10.2017 / 01:50