I have the following class:
class UserRepository { private $conn; public function __construct($conn) { $this->$conn = $conn; } //Methods omitted }
I use the following to create a UserRepository object:
$conn = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_DATABASE, DB_USERNAME, DB_PASSWORD); $userRepository = new UserRepository($conn);
I’m getting the following error in the constructor of the UserRepository:
Recoverable fatal error: Object of class PDO could not be converted to string
What am I doing wrong?
Advertisement
Answer
Your constructor uses the variable as dynamic attribute-name. Therefore it tries to convert it to a string. $this->{$conn} = $conn
vs. $this->conn = $conn
.
public function __construct($conn) { $this->conn = $conn; }