Skip to content
Advertisement

What am I doing wrong with my optional PHP arguments?

I have a the following class:

JavaScript

So from my interpretation I should be able to pass either $id or $humanIdentifier to that constructor, neither or both if I wanted. However, when I call the code below I am finding that its the $id in the constructor args being set to hello world and not the $humanIdentifier, despite me specifying the $humanIdentifier when calling the constructor. Can anyone see where I am going wrong?

JavaScript

Advertisement

Answer

Edit: As of PHP8, named arguments are now supported. This wasn’t the case at the time of this post.

PHP does not support named arguments, it will set the value according to the order in which you pass the parameters.

In your case, you’re not passing $humanIdentifier, but the result of the expression $humanIdentifier='hello world', to which $this->id is later set.

The only way I know to mimick named arguments in PHP are arrays. So you could do (in PHP7) :

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