1

Default parameters in PHP

in this article I will show you how to determine default variables in the function in PHP, because if you are new in this world of programming lenguages, you will notice that there are useful tricks at the moment to write code.

But because this is a PHP course, i will show an useful trick that can be very useful at particular situations, but it is important to know that it exist.

This trick is how we can determine a “default” parameters in a function. For example, this is pretty useful if we forget to type a parameter, because thanks to the default parameter out code will run without any mistake.

Pay attention to the next code:

<html>
        <head>
                <title>This is a sample</title>
        </head>
        <body>
                <?php
                        function increase($number, $sample = 5){
                                return $number + $sample;
                        }

                        print increase(10)."\n";
                ?>
        </body>
</html>

As you can see, the parameter that have a default value in the increase function is the variable $sample, which default value is 5. I hope you have noticed that when I printed the function I “forgot” to put the second parameter but even with this “fault” the code doesn’t break itself. The result is the following:

<html><head><title>This is a sample</title></head><body>
                15
        </body></html>

But what happen if I add the second parameter?

<html>
        <head>
                <title>This is a sample</title>
        </head>
        <body>
                <?php
                        function increase($number, $sample = 5){
                                return $number + $sample;
                        }

                        print increase(10, 10)."\n";
                ?>
        </body>
</html>

The result is the following:

<html><head><title>This is a sample</title></head><body>
                20
        </body></html>

So, maybe you can say something like “Good to know a curious trick in php” but remember it, it can be very useful in the future, either in your first web page or even at the moment to give a good impresion in your next job interview.

Escribe tu comentario
+ 2