I am new to OOP (PHP) and just met the design pattern – singleton.
I have found a DB class which uses mysqli (singleton class). I have added some custom methods to it (insert_id(), query(), fetch_result(), etc).
Then I created a new class called UserTools and I want to extend the database class to use the methods I’ve created previously (query(), fetch_result(), etc).
But I get this error:
Fatal error: Call to private Database::__construct() from invalid context in (…)
when I try to create instance of the new class (User Tools).
What should I do? Is it a right structure?
There are several way to achieve what you want.
One would be :
Although it would be better to directly pass the database instance to the constructor like this :
If you’re really lazy you could just modify your database class and make the constructor public :
But I really discourage you to use the latter one. It’s really bad code and it doesn’t make sense in a logical point of view. Your UserTools class use a database instance. It is not a database.