Php param default value

Default Function Parameters In PHP

Note: This post is over two years old and so the information contained here might be out of date. If you do spot something please leave a comment and we will endeavour to correct.

When creating functions in PHP it is possible to provide default parameters so that when a parameter is not passed to the function it is still available within the function with a pre-defined value. These default values can also be called optional parameters because they don’t need to be passed to the function. I have seen this sort of code being used incorrectly quite often recently so I thought I would go over it in a post.

Creating a default parameter in a function is very simple and is quite like normal variable assignment. The following function has a single parameter that is set to 1 if it is not passed when calling the function.

This function doesn’t do very much, but can be used in the following way. If the parameter isn’t added to the function call then the default value is used, if it is added then this value is used instead.

It is possible to use as many default arguments as is needed in a function. The following function has four parameters, three of which are optional.

This function can be run in the following manner.

It is also possible to use arrays as default parameters as in the following function.

One important thing to remember when creating default parameters is that you should add them to the end of the required parameters that your function has. It is syntactically valid to write a function in which the default parameters are not at the end of function definition, but this will lead to problems. Take the following function.

It is impossible to actually use any default parameters that are set before any non-default parameters. In the case of the code above $b will never be available as the default value of 1. PHP has no way of knowing that you want to skip a particular parameter and will therefore assign them as it always will do, in the order they are passed. Trying to skip out one of the parameters will lead to a syntax error.

Just in case some of you are thinking that it should be possible to simply add a null value as the parameter you should note that this will not work either. What you are essentially doing is passing a value (null in this case) and so the default parameter will not be used. Using the above function the following code will print 3. This is the result of the sum 1 + null + 1 + 1, the null value translates to 0 when used in a calculation.

Читайте также:  Php найти все закрывающие теги

Default parameters can be used to control the function in some way. Lets say that you wanted to create a function that will print out a variable if the function is told to do so. To do this you would create a second optional parameter that would print a given value if true is passed.

This function style can be seen in many CMS systems, usually within template functions, and can be run in the following way.

The mistake I have seen the most often is when programmers copy and paste the function definition and use this as the function call itself. The following (perfectly legal) code calls the testMultiFunction() example function above.

What we are doing here is defining the variables $b, $c and $d to be 1, which are then passed to the function in the form of parameters. In PHP it is possible to run code within function calls, the outcome of which is then passed to the function. However, this is a little wasteful as all we are doing here (and what usually happens) is defining variables that never get used after this function call. To tidy up this code just remove the variable definitions and keep the values that you want to pass to the function.

This has the same output as the previous code, but it is a much cleaner way to call the function. If you are worried about not being able to tell what parameter does what then add a comment before the function call that gives you more information.

Phil Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK. Graduating in 2003 from Aberystwyth University with an MSc in Computer Science Phil has previously worked as a database administrator, on an IT help desk, systems trainer, web architect, usability consultant, blogger and SEO specialist. Phil has lots of experience building and maintaining PHP websites as well as working with associated technologies like JavaScript, HTML, CSS, XML, Flex, Apache, MySQL and Linux.

Читайте также:  Питон по английски произношение

Want to know more? Need some help?

Let us help! Hire us to provide training, advice, troubleshooting and more.

Support Us!

Please support us and allow us to continue writing articles.

Источник

Php param default value

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

PHP Default Parameters

Summary: in this tutorial, you’ll learn about PHP default parameters and default parameters to simplify the function calls.

Читайте также:  Float в питоне зачем

Introduction to the PHP default parameters

The following defines the concat() function that concatenates two strings with a delimiter:

 function concat($str1, $str2, $delimiter) < return $str1 . $delimiter . $str2; >Code language: HTML, XML (xml)

When you call the concat() function, you need to pass exactly three arguments. For example:

 function concat($str1, $str2, $delimiter) < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!', ' '); echo $message;Code language: HTML, XML (xml)

However, you’ll find that you often use the space ‘ ‘ as the delimiter. And it’s repetitive to pass the space whenever you call the function.

This is why default parameters come into play.

PHP allows you to specify a default argument for a parameter. For example:

 function concat($str1, $str2, $delimiter = ' ') < return $str1 . $delimiter . $str2; >Code language: HTML, XML (xml)

In this example, the $delimiter parameter takes the space as the default argument.

When you call the concat() function and don’t pass the delimiter argument, the function will use the space for the $delimiter like this:

 function concat($str1, $str2, $delimiter = ' ') < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!'); echo $message;Code language: HTML, XML (xml)

However, if you pass an argument for the $delimiter , the function will use that argument instead:

 function concat($str1, $str2, $delimiter = ' ') < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!', ','); echo $message;Code language: HTML, XML (xml)

In this example, we passed a comma to the $delimiter . The concat() function used the comma ( , ) instead of the default argument.

When you specify a default argument for a parameter, the parameter becomes optional. It means that you can pass a value or skip it.

Default arguments

The default arguments must be constant expressions. They cannot be variables or function calls.

PHP allows you to use a scalar value, an array, and null as the default arguments.

The order of default parameters

When you use default parameters, it’s a good practice to place them after the parameters that don’t have default values. Otherwise, you will get unexpected behavior. For example:

 function concat($delimiter = ' ', $str1, $str2) < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!', ','); echo $message; Code language: HTML, XML (xml)

Summary

  • Use default parameters to simplify the function calls.
  • Default parameters are optional.

Источник

Оцените статью