tags:

views:

67

answers:

5

what is the difference between these functions ? and why we are assigning an empty value to a function parameter ?

function prints($var = '') {
echo $var; }

function prin($var) {
echo $var; }

Both prints the same result.

what will happen if we assign an empty value to a function parameter ?

+2  A: 

These functions will work in an identical way will show the same effect, because the default $var = '' is as if you would not assign a default value at all.

The difference between the two functions, as @Gumbo correctly points out is that prin() can't be called without specifying $var, but prints() can.

If you call the function with an empty parameter, $var will simply be empty.

Pekka
A: 

That's a default parameter

http://php.net/manual/en/functions.arguments.php

So for your sample calling prints() will echo an empty string and calling prin() will throw an error because the parameter is missing.

mattanja
A: 

The first one has a default value for the variable $var.

You might be interested in reading the PHP manual page on function arguments.

Thomas Owens
A: 

The function

function prints($var = '')

receives a default value (which is an empty value in this case).

The other function doesn't receive it. This means, that you can call the first function prints() with no parameter, and it'll treat it as if you called it with an empty string - prints('').

You can't call the second function without the defined parameter, as it doesn't set a default value, and will issue an error.

Doron
+3  A: 

The first function has a default value for its first parameter. That means that parameter doesn’t need to be specified when calling that function.

So you can call the first function without the parameter like this:

prints();

And the default value for the first parameter is used. But when calling the second function the parameter needs to given:

prin('parameter');

If you call it without that parameter (prin()), you’ll get a warning like:

Warning: Missing argument 1 for prin(), called in …

Gumbo
Shame on me - of course there's a difference. +1
Pekka
Thanks to all Replies. :-)
paulrajj