Skip to content
Advertisement

How do I pass specific optional arguments?

I have 2 cases.

  • Case 1: pass the name and age.
  • Case 2: pass name and gender.

How can I do this?


JavaScript

Advertisement

Answer

You can have optional arguments in PHP, but you cannot have either/or arguments as that would require function overloading which is not supported in PHP. Given your example, you must call the constructor as follows:

JavaScript

If you want to eliminate the optional but required to be null argument, you will need to get clever.

Option One: Use a factory. This would require a common argument constructor in conjunction with mutator methods for each of the unique arguments.

JavaScript

The factory doesn’t need to be a separate class, you can alternatively add the static initializers to the User class if desired.

JavaScript

Option Two: Do some argument detection. This will only work if the arguments are all unique types.

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