Skip to content
Advertisement

PHP A Good way to pass the PDO Object into other Main classes

im new to PHP OOP, now i was woundering if there is a better way to use the Database Class then just extending it over all.

For Example i am having 3 main classes: Employee, Customer, Article. each of this classes have a subclasses which extends form. what i have done until now is extand the Db class on each of these 3 main classes.

My DB class:

JavaScript

one Of the Main classes (Employee):

JavaScript

then there is a sub class of Employee called EmployeeMng. this subclass contains functions such as login or signup. also this subclass handles the POST requests coming froom the client side.

JavaScript

Now i tried to declare the db class in the Employee constructor. but i keep getting the error Call to protected DbController::__construct() from scope Employee. is there a clean way to do that?

Advertisement

Answer

In general, you’d create your database object outside of this class and then inject it as a parameter. This is called Dependency Injection and is a Good Thing™.

Then you’d use that parameter within your class-specific methods. So your employee class would look something like this:

JavaScript

And then to use that class, you’d instantiate a database object, and then pass that to the Employee:

JavaScript

You should not do this:

JavaScript

Or this:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement