2

I am having trouble with naming the function. I have a class and I need 2 functions something like below.

class myclass {
    public function tempclass () {
        echo "default";   
    }
    public function tempclass ( $text ) {
        echo $text;
    }
}

When I call

tempclass('testing'); // ( called after creating the object )

function tempclass() is being called how can i have 2 functions with same name but different parameters?

1
  • Why do you use quote formatting instead of code formatting for your code? Commented Apr 20, 2012 at 15:21

2 Answers 2

5

Traditional overloading is not currently possible in PHP. Instead you'll need to check the arguments passed, and determine how you'd like to respond.

Check out func_num_args and func_get_args at this point. You could use both of these internally to determine how you should respond to the invocation of certain methods. For instance, in your case, you could do the following:

public function tempclass () {
  switch ( func_num_args() ) {
    case 0:
      /* Do something */
      break;
    case 1:
      /* Do something else */
  }
}

Alternatively, you could provide default values for your arguments as well, and use those to determine how you ought to react:

public function tempclass ( $text = false ) {
  if ( $text ) {
    /* This method was provided with text */ 
  } else {
    /* This method was not invoked with text */
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1, but suggest editing your answer to include reference links to func_get_args() and func_num_args(). :-)
0

Overloading isn't possible in PHP.

However, for your simple example above, something like this would work:

class myclass {
    public function tempclass ($text='Default') {
        echo $text;
    }
}

3 Comments

Made a change that I think that you may agree with.
Completely! Didn't even think of that =)
Your on-line contact form does not work. You live in Scotland, so do I. My contact details are available through this sight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.