1

I am making a class with a couple function that requires some SQL stuff, and I do not want define a new PDO object for every function, but have a one that works on all functions.

This is what I got so far:

<?php
class UserSystem
{
    public $mysqlDetails = 
    [
        "host"        => "127.0.0.1",
        "user"        => "",
        "pass"        => "",
        "database"    => "",
        "table"       => ""
    ];

    public $con = new PDO
    (
        "mysql:host=" . $this->mysqlDetails['host'] .
        ";dbname=" .    $this->mysqlDetails['database'] . ";",
                        $this->mysqlDetails['user'],
                        $this->mysqlDetails['pass']
    );

How could I get this to work? Currently I get this error: Parse error: syntax error, unexpected 'new' (T_NEW). Is there a better way to do this, so I can use the $con variable in functions without having to create a new one. I do not want to inject it into functions as I've seen suggested. IE this:

<?php
function someFunc ($pdo)
{
    $pdo->query("SELECT * FROM `someTable`");
}
  • Instead of initializing PDO inside the class you should inject it as a dependency. You can use [this](http://stackoverflow.com/a/11369679/727208) approach as basis and improve upon. Your current implementation violates several of [SOLID](http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) principles. – tereško Oct 10 '13 at 21:57

1 Answers1

1

You cannot initialize class properties with anything but compile time resolvable constant values. You'll have to create the PDO object in the constructor:

public function __construct() {
    $this->con = new PDO(...);
}

Better yet, you should make your class accept a PDO object and dependency inject it, since I'd be guessing you need a database connection in more than just this one class, and you don't want to connect to the same database again and again in different classes:

public function __construct(PDO $con) {
    $this->con = $con;
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thank you, I am using a constructor now which solved all my problems in a nice clean simple way. I make a private variable $con and then set it in the constructor, if anyone reading this has the same problem. – Dan Lindqvist Oct 10 '13 at 15:57