user656925
user656925

Reputation:

PHP Function Overloading - How to?

public function makeTweet( $DatabaseObject, $TextObject, $MessageObject)
{
    if( $DatabaseObject == NULL )
    {
        $DatabaseObject = new Database();
        $TextObject = new Text();
        $MessageObject = new Message();
    }
    $TweetObject = new ControlTweet();        
    $TweetObject->setObjects($DatabaseObject, $TextObject, $MessageObject);
    return $TweetObject;
}

Upvotes: 2

Views: 224

Answers (3)

iambriansreed
iambriansreed

Reputation: 22241

PHP functions can be "overloaded". Use func_get_args and set no variables in the function.

You could also submit an associative array as a single variable. Then you can use extract inside the function to make friendly variables.

$vars = array('key1'=>'value1','key2'=>'value3');

function function_name($v){
     extract($v);

    //do something
}

For the function to behave differently you would need to determine what your variables are. In this way you can mirror the overloading idea.

Upvotes: -1

PeeHaa
PeeHaa

Reputation: 72662

You can add optional parameters in the function declaration like:

public function makeTweet( $DatabaseObject, $TextObject, $MessageObject = null)

Now you can either do:

$obj->makeTweet($db, $text, $messageObj);

or

$obj->makeTweet($db, $text);

This is the closest you can get in PHP.

Upvotes: 1

RyanS
RyanS

Reputation: 4194

You cannot overload a function in PHP. See this page for reference: http://www.daniweb.com/web-development/php/threads/19978/overloading-php-functions

Upvotes: 1

Related Questions