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`");
}
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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments