joedborg
joedborg

Reputation: 18353

PHP classes and functions optional arguments

Is this not meant to work in PHP?

<?php
function shout($mute="", $message="") {
    echo $message;
}

shout($message = "Boo");
?>

I know this is a poor example, but it gets my point across.

Upvotes: 1

Views: 84

Answers (3)

jugnu
jugnu

Reputation: 139

in php passing function parameters is conventional,

suppose you have a function definition like this function myfunc($arg='something or null' , $arg) this is the wrong way as we have to put our constants on right side of the function like this

function myfunc($arg, $arg='something or null'){}

when you are calling function make sure you are passing correct arguments i.e myfunc('test')

if you described $arg='null' then you dont need to pass anyhing from your function call because null is a value whereas empty string is nothing.

so in your case you must do like this function yourfunction('value1','value2')

Upvotes: 0

Dunhamzzz
Dunhamzzz

Reputation: 14798

No this won't work, function parameter order is strict and cannot be manipulated.

You can either do this:

shout(null, 'Boo');

Or re-factor your function to accept an array:

function shout($args) {
    echo $args['message'];
}

$args = array('message' => 'boo');
shout($args);

Upvotes: 1

Naftali
Naftali

Reputation: 146310

<?php
function shout($mute="", $message="") {
    echo $message;
}

shout(null, "Boo"); //echo's "Boo"
?>

You have to pass in the correct parameters in the correct order.

Upvotes: 1

Related Questions