Functions
Write and call a function
displayName(); function displayName() { echo "Client A"; }
Client A
Function with arguments (parameters)
addNumbers(10, 10) function addNumbers($value1, $value2) { echo ($value1 + $value2); }
20
Return value from the function
$answer = subtractNumbers(10, 10); echo $answer; function subtractNumbers($value1, $value2) { $result = ($value1 - $value2); return $result; }
0
Strict type
declare(strict_types=1); // enable strict type $answer = multiplyNumbers(10, 10); // must pass the value that will match with the argument type when strict type is enabled echo $answer; // This method receives int type values and the return type is also int i.e. : int { function multiplyNumbers(int $value1, int $value2) : int { $product = ($value1 * $value2); return $product; }
100
declare(strict_types=1); // enable strict type $evenNumbersList = getEvenNumbersOnly(10); echo var_dump ($evenNumbersList); function getEvenNumbersOnly(int $value) : array { $evenNumbers = []; for ($i=1; $i <= $value; $i++) { if ($i % 2 == 0) { $evenNumbers[] = $i; } } return $evenNumbers; }
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
bool(true)
Optional argument
displayRange(1); function displayRange (int $start, int $end = 100) { echo "Range: "$start . " to " . $end; }
Range: 1 to 100
Dynamic Function
$doubleIt = "doubleTheValue"; $doubleIt (5); function doubleTheValue (int $value) { echo ($value * 2); }
10
Anonymous/Closure Function
$doubleIt(5); $doubleIt = function (int $value) { echo ($value * 2); };
10
$input = 10; $doubleIt = function() use ($input) { // anonymous function can access variable defined outside with the use keyword. echo ($input * 2); }; $doubleIt();
20
Arguments as reference
$input = "Good"; getGreetings(); echo $input function (string &$input) { $input = $input . "Morning"; }
Good Morning