PHP Β· Les 6
Functies
Declareren, parameters, typed return, scope, anonymous en arrow functions Β· 25 min
Functies declareren
<?php
// Basis functie
function begroet($naam) {
return "Hallo, $naam!";
}
echo begroet("Jan"); // Hallo, Jan!
echo begroet("Marie"); // Hallo, Marie!
// Functie met meerdere parameters
function berekenOppervlak($breedte, $hoogte) {
return $breedte * $hoogte;
}
echo berekenOppervlak(5, 3); // 15
// Functie zonder return β void
function logBericht($bericht) {
echo "[LOG] $bericht\n";
}
logBericht("Server gestart");
// Functies zijn hoisted in PHP β je kunt ze voor declaratie aanroepen
$resultaat = optellen(3, 4);
function optellen($a, $b) {
return $a + $b;
}
echo $resultaat; // 7
β οΈ Let op verschil met JS
De function-syntax is identiek aan JavaScript. Net als JS zijn PHP-functies gehoisted (te gebruiken voor declaratie). Groot verschil: in PHP beginnen parameters altijd met $.
Type hints (PHP 7+ / 8)
Met type hints vertel je PHP welk type een parameter of return-waarde moet hebben. PHP gooit een fout als het type niet klopt.
<?php
// Parameter- en return-type declareren
function optellen(int $a, int $b): int {
return $a + $b;
}
echo optellen(3, 4); // 7
// optellen("3", 4); // TypeError in strict mode
// Float
function bereken(float $prijs, float $tarief): float {
return $prijs * (1 + $tarief);
}
// String
function begroet(string $naam): string {
return "Hallo, $naam!";
}
// Bool
function isVol(int $huidig, int $max): bool {
return $huidig >= $max;
}
// Nullable type β parameter mag ook null zijn
function zoekGebruiker(?int $id): ?string {
if ($id === null) return null;
return "Gebruiker #$id";
}
// void β geen return waarde
function log(string $bericht): void {
echo "[LOG] $bericht\n";
}
// Union types (PHP 8)
function verwerk(int|string $invoer): string {
return "Ontvangen: $invoer";
}
π Komt terug in Symfony
Symfony gebruikt type hints overal: controllers, services, entities. Symfony's Dependency Injection gebruikt type hints om automatisch de juiste service te injecteren. public function index(EntityManagerInterface $em): Response β Symfony weet welke service te injecteren op basis van het type.
Standaardwaarden en variabele argumenten
<?php
// Standaardwaarden β optionele parameters altijd ACHTERAAN
function begroet(string $naam, string $aanhef = "Hallo"): string {
return "$aanhef, $naam!";
}
echo begroet("Jan"); // Hallo, Jan!
echo begroet("Jan", "Goedemorgen"); // Goedemorgen, Jan!
// Meerdere standaardwaarden
function maakUrl(
string $pad,
string $protocol = "https",
int $poort = 443
): string {
return "$protocol://mbo-sd.com:$poort/$pad";
}
echo maakUrl("php-1"); // https://mbo-sd.com:443/php-1
echo maakUrl("api", "http", 80); // http://mbo-sd.com:80/api
// Variabele argumenten met ...
function som(int ...$getallen): int {
return array_sum($getallen);
}
echo som(1, 2, 3, 4, 5); // 15
// Spread operator bij aanroepen
$nums = [1, 2, 3];
echo som(...$nums); // 6
β οΈ Let op verschil met JS
Standaardwaarden werken hetzelfde als in JS. De spread ... operator werkt ook vergelijkbaar. Verschil: in PHP kun je alleen standaardwaarden geven aan parameters die aan het einde staan β net als in JS.
Scope
PHP-functies hebben een eigen scope. Variabelen van buiten zijn niet automatisch beschikbaar.
<?php
$buitenste = "ik ben buiten";
function testScope() {
// $buitenste is hier NIET beschikbaar
echo isset($buitenste) ? "beschikbaar" : "niet beschikbaar";
echo "\n";
}
testScope(); // "niet beschikbaar"
// global keyword β vermijd dit in moderne PHP
$teller = 0;
function verhoog() {
global $teller;
$teller++;
}
verhoog();
echo $teller; // 1
// Beter: geef door als parameter en return
function verhoogNetjes(int $teller): int {
return $teller + 1;
}
$teller = verhoogNetjes($teller);
echo $teller; // 2
β οΈ Let op verschil met JS
In JavaScript kunnen functies variabelen uit de buitenste scope lezen via closures β automatisch. In PHP werkt dat niet: je hebt global of use nodig. Dit is een van de grootste verschillen tussen PHP en JS.
Anonymous functions en arrow functions
<?php
// Anonymous function (closure)
$verdubbel = function(int $n): int {
return $n * 2;
};
echo $verdubbel(5); // 10
// use β importeer buitenste variabele in closure
$factor = 3;
$vermenigvuldig = function(int $n) use ($factor): int {
return $n * $factor;
};
echo $vermenigvuldig(4); // 12
// use by reference β wijzig de buitenste variabele
$teller = 0;
$verhoog = function() use (&$teller): void {
$teller++;
};
$verhoog(); $verhoog();
echo $teller; // 2
// Arrow function (PHP 7.4+) β vangen automatisch buitenste scope
$factor = 5;
$fn = fn(int $n) => $n * $factor; // $factor automatisch beschikbaar
echo $fn(3); // 15
// Gebruik als callback
$nummers = [1, 2, 3, 4, 5];
$gekwadrat = array_map(fn($n) => $n ** 2, $nummers);
print_r($gekwadrat); // [1, 4, 9, 16, 25]
// Functies meegeven als argument (higher-order functions)
function toepassen(array $arr, callable $fn): array {
return array_map($fn, $arr);
}
$verdubbeld = toepassen([1,2,3], fn($n) => $n * 2);
print_r($verdubbeld);
β οΈ Let op verschil met JS
PHP arrow functions (fn($x) => expr) vangen automatisch de outer scope, net als JS arrow functions.
PHP closures (function() {}) vangen de outer scope niet automatisch β je hebt use ($var) nodig. Dit verschilt van JS.
π Komt terug in Symfony
Arrow functions gebruik je dagelijks in Symfony bij Doctrine-queries: $producten = array_filter($alle, fn($p) => $p->isActief());. En in Symfony's event listeners en middleware-chains.
Sandbox
Schrijf functies met type hints en experimenteer met arrow functions.
// output
Klik op Uitvoeren...
Kennischeck
Les 6 afronden
Ga door naar formulieren β