Basics of Working with User-Defined Functions in PHP
Now we will learn how to create our own functions, which can then be used like standard PHP functions.
Let's look at the syntax for creating a custom function.
A function is created using the function command.
Next, after a space, comes the function name
and parentheses, inside which
some code is written:
<?php
function func() {
// some code
}
?>
Let's look at an example.
Let's make a function named func that,
when called, will output
an exclamation mark:
<?php
function func() {
echo '!';
}
?>
Now let's call our function. To do this, you need to write its name and parentheses:
<?php
function func() {
echo '!';
}
// Call our function:
func(); // outputs '!'
?>
You can call our function several times - in this case, each function call will perform a new output:
<?php
function func() {
echo '!';
}
func(); // outputs '!'
func(); // outputs '!'
func(); // outputs '!'
?>
Functions can be called before their definition:
<?php
func(); // outputs '!'
function func() {
echo '!';
}
?>
Create a function that outputs your name.
Create a function that outputs the sum
of numbers from 1 to 100.