StevenPHP
StevenPHP

Reputation: 3607

php - Function variable declared to null. Why?

I have been editing an existing php script and have come across a function as so

function functionName($var1 = null, $var2 = null, $var3 = null)

I'm not sure why you would declare a var as null in this way. I have tried looking for an answer online but google pulls up anything but this example.

Any help would be greatly appreciated.

Upvotes: 2

Views: 2190

Answers (4)

Amal Murali
Amal Murali

Reputation: 76636

The function is defined with NULL as the identifier of the default variable. See example #3 on the documentation for functions in the PHP manual.

The argument $var1 is optional and is not required. If specified, the given value will be used. If not, the value specified as the default value will be used.

Another example:

function sayHello($person = 'stranger') {
    return "Hello, $person";
}

echo sayHello('Rob');
echo sayHello('Tom');
echo sayHello();

It will output:

Hello, Rob
Hello, Tom
Hello, stranger

Refer to the PHP manual for more information.

Hope this helps!

Upvotes: 1

rray
rray

Reputation: 2556

when you put in a value into a parameter like this mean, if you don't pass a nothing 'lol'(or other value) will be default.

   function foo($param1 = 'lol'){
     echo $param1;
   }


   foo(); //'lol';
   foo('new foo'); // new foo

Upvotes: 0

Raphaël Malié
Raphaël Malié

Reputation: 4012

It's just a default value : when you call the function, if you don't set a value to $var it will take the default one.

For example :

function foo($bar = 'default')
{
    return $bar;
}

echo foo(); // Will display "default"
echo foo('Hello world!'); // Will display "Hello world!"

Upvotes: 0

Pekka
Pekka

Reputation: 449623

These are default values: you don't have to specify them when you call the function. When you omit them, the default value will be used.

See example #3 on this manual page. From there:

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

will output

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

Upvotes: 3

Related Questions