We’ve already presented many examples of function calls in the previous tutorials. Once written, a user-defined function is called in exactly the same way.
<?php function functionName () { }
A user-defined function declaration starts with the word function
, function name, ( )
brackets for arguments and { }
brackets for the function’s code block. The following example demonstrates how to create and use a simple user-defined function:
<?php function printEmail() { echo 'info@BrainBell.com'; } echo printEmail(); # Prints: info@BrainBell.com
The above code declares a function printEmail()
, when you call this function, it prints the email address.
You don’t need to predeclare a function before you call it. PHP parses the entire file before it begins executing, so you can call the printEmail() function before declaring it:
<?php echo printEmail(); # Prints: info@BrainBell.com function printEmail() { echo 'info@BrainBell.com'; }
You can declare arguments (also known as parameters) to the function, which allows you to pass values to the function. Parameters are passed as a comma-separated list and are evaluated left to right:
<?php function add($a, $b) { echo $a + $b; } $x = 2; $y = 5; add ( $x , $y ); # Prints: 7
Functions can return values. For example, consider the following code fragment that declares and calls a function add()
that returns the result using the return
statement:
<?php function add($a, $b) { return $a + $b; } $x = 2; $y = 5; $z = add ( $x , $y ); echo $z; # Prints: 7
Note: return
statement can optionally be placed in parentheses: the statements return($result)
and return $result
are identical.
Argument Types and Return Types
PHP is a loosely typed language it allows arguments of any type to be passed to the function, and as with variables, the return type is determined when a result is actually returned. Consider a simple function that divides two numbers:
<?php function divide($a, $b) { return ($a/$b); } $c = divide(4, 2); # assigns an integer value = 2 $c = divide(3, 2); # assigns a float value = 1.5 $c = divide(4.0, 2.0); #assigns a float value = 2.0
If the types of arguments passed to the function are critical, you can specify what type of variables may be passed as arguments:
<?php declare(strict_types = 1); function divide(float $a, float$b): float { return ($a/$b); }
In above example, we’ve declared strict_types = 1
directive to enable the PHP’s strict mode. In strict mode, only a variable of the exact type of the “type declaration” will be accepted. For detail, read Argument and Return Type Declaration and Strict Typing Mode tutorials.
Specify default value for a parameter (argument)
You can make an argument optional by specifying its default value. In the following example, if you do not pass the value to the function, the function assumes it will be “Hello world”:
<?php function speak($m = 'Hello world'){ return $m; } echo speak(); # Prints: Hello world echo speak('Hi'); # Prints: Hi
User-defined functions: