Reputation: 10877
I currently have the following code:
class User {
private static $_db;
public function __construct () {
self::$_db = Database::getInstance()->getConnection();
}
public static function addUser ($name, $username, $password) {
// Define Values
$name = ucwords(trim($name));
$username = strtolower(trim($username));
$password = password_hash($password, PASSWORD_BCRYPT);
// Define Query
$query = "INSERT INTO `users` (name, username, password) VALUES(:name, :username, :password)";
// Prepare Query
$preparedQuery = self::$_db->prepare($query);
// Execute Query
$preparedQuery->execute([
':name' => $name,
':username' => $username,
':password' => $password
]);
}
}
I'm trying to set a class property with my database connection through a construct. Issue is that I want to be able to access the addUser()
method anywhere in the script by simply calling User::addUser()
. Is there a way I can set a static property via a construct or is there a better way to go about accessing my database?
Upvotes: 0
Views: 895
Reputation: 990
The construct is only called when a new instance of the class is created. Since addUser()
is a static method, and thus a new instance is not created, your constructor will not get called and the static $_db
variable will never get initialized.
I would add create a static method that returns the connection to the db, and you can use that everywhere throughout your code. For example:
class User {
private static $_db;
public function __construct () {
// construct
}
public static function getDB () {
return Database::getInstance()->getConnection();
}
public static function addUser ($name, $username, $password) {
// Define Values
$name = ucwords(trim($name));
$username = strtolower(trim($username));
$password = password_hash($password, PASSWORD_BCRYPT);
// Define Query
$query = "INSERT INTO `users` (name, username, password) VALUES(:name, :username, :password)";
// Prepare Query
$preparedQuery = self::getDB()->prepare($query);
// Execute Query
$preparedQuery->execute([
':name' => $name,
':username' => $username,
':password' => $password
]);
}
}
If you wish to continue using a static property, you can create a static setter for the property (you would need to call this method at least once before calling addUser
):
public static function setDB () {
self::$_db = Database::getInstance()->getConnection();
}
Upvotes: 1