Function Parameters in PHP
When calling a function, we write its name and empty parentheses:
<?php
func();
?>
In fact, the parentheses do not have to be empty - we can pass parameters inside them.
Suppose, for example, we want to create a function that will take a number as a parameter and display the square of that number.
How we will now call our function: we will write the function name, parentheses, and inside them - some number whose square we want to get.
For example, this is how we get the square of the number
2:
<?php
func(2); // outputs 4
?>
And like this - the square of the number 3:
<?php
func(3); // outputs 9
?>
Let's now write the implementation of our function.
We know that the function should take a number as a parameter. This means that when defining the function, inside the parentheses we should write some variable that will receive the passed number.
The variable name can be anything, let's,
for example, call it $num:
<?php
function func($num) {
}
?>
This variable $num will receive
the number specified in the parentheses when the function is called:
<?php
func(2); // the number 2 will go into the variable $num
func(3); // the number 3 will go into the variable $num
?>
Let's now make our function
output the square of the passed number. To do this,
multiply the variable $num by
itself and output it:
<?php
function func($num) {
echo $num * $num;
}
?>
Let's test the function by calling it with different numbers:
<?php
function func($num) {
echo $num * $num;
}
func(2); // outputs 4
func(3); // outputs 9
?>
Create a function that takes a number as a parameter and outputs the cube of this number.
Create a function that takes a number as a parameter
and checks if this number is positive
or negative. In the first case, let the
function output the text '+++',
and in the second '---'.