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`");
}
1
  • Instead of initializing PDO inside the class you should inject it as a dependency. You can use this approach as basis and improve upon. Your current implementation violates several of SOLID principles. Commented Oct 10, 2013 at 21:57

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.