How to instantiate $Pdo = connect() without repeating?

Asked

Viewed 76 times

4

For example I have a class called user:

class User
{
    public $nome;
    private $email;
    protected $senha;

    public function __construct(){

    }

    public function insert($email, $senha){
        require_once "conexao.php";
        $pdo = conectar();

        $insertSQL = $pdo->prepare('INSERT INTO tbl (valores) VALUES (?)');
        $insertSQL->bindValue(1, $this->lalala(), PDO::PARAM_STR);
        $insertSQL->execute();
    }

and also see that I need to do the require():

require_once "conexao.php";
$pdo = connect();

But I have to do these two lines every time for every method in the class. There is no way to create a single time and be available in all class scope, like attributes?

I’ve tried as an attribute and it didn’t work. With the constructor it wasn’t either (maybe I did wrong).

  • 2

    Create a connection property in the class, it receives the connection by the constructor, whenever the object needs it will already be created.

  • Like a public $Pdo @rray? And in the require constructor and then $Pdo = connect()?

  • How so help me @rray

  • 2

    Your name is almost the same as my @LINQ

  • 1

    I found it quite different, @System.Linq

2 answers

6


A suggestion is to create a property and connection in your class and pass the connection to it via constructor. So whenever the object (from User) need a connection it will already be open.

class User
{
    public $nome;
    private $email;
    protected $senha;
    private $db; //propriedade da conexão

    //pega a conexão externa e joga dentro da propriedade
    public function __construct($db){
       $this->db = $db;
    }

    public function insert($email, $senha){
       $insertSQL = $this->db->prepare('INSERT INTO tbl (valores) VALUES (?)');
       //demais códigos ...
}

When it’s time to call

include 'conexao.php'; 
$user = new User($pdo);

//ou ainda:
$user = new User(conectar());

It does not have much advantage to create a function only to create and return the PDO connection with the user parameters and direct password in the code, in this case you can pass the direct connection variable.

  • Now went and understood thank you

-2

You can do it this way:

require_once "conexao.php";

class User
{
    public $nome;
    private $email;
    protected $senha;

    public function __construct(){

    }

    public function insert($email, $senha){
        $pdo = conectar();

        $insertSQL = $pdo->prepare('INSERT INTO tbl (valores) VALUES (?)');
        $insertSQL->bindValue(1, $this->lalala(), PDO::PARAM_STR);
        $insertSQL->execute();
    }
  • But then I’ll have to keep calling $Pdo every time in the methods I won’t?

Browser other questions tagged

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