Question

I’m new in PHP, and I want to do the same as the follow java source-code in PHP. Can anyone help me?

someMethod(int i) {
System.out.println("message");
// more code
}
someMethod(String s) {
System.out.println("another message");
// more different code
}
Was it helpful?

Solution

You cannot overload PHP functions, as their signatures only include their name and not their argument lists: https://stackoverflow.com/a/4697712/386869

You can either do two separate functions (which I recommend) for what you're trying to do, or perhaps write one function and perform a different action for each type.

Writing two methods is straightforward:

function myFunctionForInt($param)
{
    //do stuff with int
}
function myFunctionForString($param)
{
    //do stuff with string
}

If you'd like to instead do it with one function and check the type (not really recommended):

function myFunction($param)
{
    if(gettype($param) == "integer")
    {
        //do something with integer
    }
    if(gettype($param) == "string")
    {
        //do something with string
    }
}

Docs for gettype()

I don't know that it's the best way. Also, for your particular example, Imat's example makes the most sense since you're just printing a message.

OTHER TIPS

Okay, so you want to create a function that prints a message.

function my_function_name()
{
   echo "your message here;
}

If you want a function with parameters, you can do this.

function my_function_name($params)
{
    echo "your message here";
    echo $params; //call the paramereters
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top