Why doesn't PHP support traditional function overloading?

Overloading the PHP function


From C ++ background;)
How can I overload PHP functions?

One function definition when there are arguments and another when there are no arguments? Is it possible in PHP? Or should I use if else to check if parameters were passed from $ _GET and POST? and relate them?






Reply:


You cannot overload PHP functions. Function signatures are based only on their names and do not contain lists of arguments. So you can't have two functions with the same name. Class method overloading in PHP is different from many other languages. PHP uses the same word but describes a different pattern.

However, you can declare a variable function that takes a variable number of arguments. You would use and to pass the arguments and use them normally.

For example:





PHP does not support traditional method overloading. One way to get what you want is to use the magic method to use:







To overload a function, just pass the parameter as null by default.





It may be hacky to some, but that's how I learned how Cakephp performs some functions and customized it because I like the flexibility it creates

The idea is that you have different types of arguments, arrays, objects, and so on. Then you realize what has been given to you and go from there









What about it:



In PHP 5.6 you can abolish the use of Splat operator as the last parameter and and:

You can also use it to extract arguments:

Is equivalent to:






Unfortunately, there is no overload in PHP as in C #. But I have a little trick. I declare arguments with default null values ​​and check them in a function. That way, my function can do different things depending on the arguments. Below is a simple example: