Asked  7 Months ago    Answers:  5   Viewed   35 times

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

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



You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.

You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

For example:

function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %sn", $i, func_get_arg($i));

Argument 0: a
Argument 1: 2
Argument 2: 3.5
myFunc('a', 2, 3.5);
Wednesday, March 31, 2021
answered 7 Months ago

You can use either:

example($argument1, '', 'test');


example($argument1, NULL, 'test');

You can always check for NULL using instead of empty string:

if ($argument === NULL) {

I think it all depends on what happens inside the function with the args.

Wednesday, March 31, 2021
answered 7 Months ago

Check if the declaring class matches the class of the object:

$reflector = new ReflectionMethod($ob, 'createTable');
$isProto = ($reflector->getDeclaringClass()->getName() !== get_class($ob));

PHP Manual links:

  • ReflectionMethod
  • ReflectionProperty
Saturday, May 29, 2021
answered 5 Months ago

Declare your arguments as Optional Variants, then you can test to see if they're missing using IsMissing() or check their type using TypeName(), as shown in the following example:

Public Function Foo(Optional v As Variant) As Variant

    If IsMissing(v) Then
        Foo = "Missing argument"
    ElseIf TypeName(v) = "String" Then
        Foo = v & " plus one"
        Foo = v + 1
    End If

End Function

This can be called from a worksheet as =FOO(), =FOO(number), or =FOO("string").

Wednesday, June 30, 2021
answered 4 Months ago

add these code into the top of your script

ini_set('magic_quotes_runtime', 0);
Wednesday, August 18, 2021
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :