Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword function

Declare a named function with parameters, an optional return type and a body.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

function fee(int $n = 2): int { return $n * 3; }

Declare a named function with parameters, an optional return type and a body. Each ordinary call has its own local variables. A default argument applies when omitted. A conditional declaration becomes available only after that declaration executes. Anonymous functions yield Closure objects. An unconditional top-level function may be called earlier in the same file than its declaration.

echo early(),"\n"; function early(){return "early";}
function fee(int $n=2):int {$rate=3;return $n*$rate;}
$before=function_exists("badge"); if(true){function badge(){return "ok";}}
echo json_encode([fee(),fee(4),$before,badge()]);
early
[6,12,false,"ok"]

Examples

<?php
echo early(),"\n"; function early(){return "early";}
function fee(int $n=2):int {$rate=3;return $n*$rate;}
$before=function_exists("badge"); if(true){function badge(){return "ok";}}
echo json_encode([fee(),fee(4),$before,badge()]);

Result

early
[6,12,false,"ok"]

Sources