Victor's Blog about PHP, Zend Framework & Cake PHP

This blog is about PHP in general. It tackles various topics related to the language itself especially at the OOP level, discusses various topics related to Zend Framework and shares my experience with Cake PHP. I believe that mastering technology is heavily based on one's ability to discuss its details and share knowledge with others. Technology is a wide wild world after all!

PHP Function Overloading

Printable Version

victor | 16 November, 2010 07:24

All Object Oriented languages (or almost all of them) support function overloading where programmers are allowed to define multiple functions with the same name but with separate "function signatures". A function signature is usually the number of parameters, the order of parameters and / or the type of parameters.

For example, in Java, you are allowed to define the following:

public void testFunction (int x) { ... }

public void testFunction (int x, int y) { ... }

public void testFunction (int x, double y) { ... }

By defining the above, the Java Virtual Machine will automatically invoke the appropriate function once called based on the number and type of parameters given. For example, invoking

testFunction (2);

will automatically invoke the first function while invoking

testFunction (2, 3.1);

will automatically invoke the third function.

PHP, on the other hand, does not have support for function overloading yet. Defining the same function more than once with a different number of paramters will surely (so far) generate an error at the parser level.

It is still possible to simulate function overloading in PHP using parameters default values. Upon function definition, simply provide default values to parameters as follows:

function testFunction ($a = false, $b = false, $c = false) { .... }

By doing so, you will be defining a function that takes 3 arguments ($a, $b, and $c) whose default value is false.

Within the function body, you will then simply check whether the value of the parameter that is being passed is still false and act accordingly.

Remember, though, that PHP provides automatic data type conversion. In other words, if the value of $b is 0 (Zero) and you check whether $b is false using the equality operator (==), you will get a true value returned. As such, remember to use the data typed equality operator (===) instead of the normal operator (==).

 

Related Articles:

Comments

Add comment
 
Accessible and Valid XHTML 1.0 Strict and CSS