forked from bradtraversy/php-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_functions.php
57 lines (43 loc) · 955 Bytes
/
06_functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
/* ------------ Functions ----------- */
/*
** Function Syntax
function functionName($arg1, $arg2, ...) {
// code to be executed
}
- Functions have their own local scope as opposed to global scope
*/
function registerUser()
{
echo 'User has been registered!';
}
// Running a function
registerUser();
// Adding params
function registerUser2($username)
{
echo "User ${username} has been registered!";
}
// Pass in an argument
registerUser2('Brad');
// Returning values
function add($num1, $num2)
{
return $num1 + $num2;
}
$sum = add(5, 5);
echo $sum;
// Adding default values
function subtract($num1 = 10, $num2 = 5)
{
return $num1 - $num2;
}
echo subtract();
// Assigning anonymous functions to variables. Often used for closures and callback functions
$add = function ($num1, $num2) {
return $num1 + $num2;
};
echo $add(5, 5);
// Arrow functions
$multiply = fn($num1, $num2) => $num1 * $num2;
echo $multiply(5, 5);