Skip to content
Advertisement

Best way to do multiple constructors in PHP

You can’t put two __construct functions with unique argument signatures in a PHP class. I’d like to do this:

JavaScript

What is the best way to do this in PHP?

Advertisement

Answer

I’d probably do something like this:

JavaScript

Then if i want a Student where i know the ID:

JavaScript

Or if i have an array of the db row:

JavaScript

Technically you’re not building multiple constructors, just static helper methods, but you get to avoid a lot of spaghetti code in the constructor this way.

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