Create your own functions with typed parameters, default values, and return values.
Open this lesson in KodokonA function is a block of instructions you give a name to, so you can reuse it as many times as needed with a simple call. Write once, use everywhere: that's the principle. You declare it with the function keyword, followed by the name, parentheses, and a block inside braces. The : void marking after the parentheses says the function returns nothing: it simply acts.
<?php
function sayHello(): void
{
echo "Hello and welcome!<br>";
}
sayHello();
sayHello();The parentheses hold the parameters: variables the function receives on each call. The concrete value supplied when calling is called an argument. In modern PHP, you type each parameter (float $price) and the returned value (: float after the parentheses): PHP then refuses values of the wrong type, which prevents many bugs. The return statement sends a result back to the call site and immediately stops the function.
<?php
function addTax(float $price): float
{
return $price * 1.2;
}
echo addTax(100);
echo "<br>";
echo addTax(50);A parameter can receive a default value with =: if the call doesn't provide an argument for that parameter, the default value takes over. Golden rule: parameters with defaults go after the required ones.
<?php
function greet(
string $name,
string $greeting = "Hello"
): string {
return "{$greeting}, {$name}!";
}
echo greet("Awa");
echo "<br>";
echo greet("Awa", "Good evening");<?php
function totalPrice(
float $unitPrice,
int $quantity = 1
): float {
return $unitPrice * $quantity;
}
echo totalPrice(19.9, 3);
echo "<br>";
echo totalPrice(8.5);deffunctionfuncreturn statement do?function greet(string $name, string $greeting = "Hello"), what is $greeting if you call greet("Awa")?null