Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / PHP

Typ PHP callable

Parameter callable prijíma Closure alebo iný volateľný tvar, napríklad dvojicu objekt a názov verejnej metódy.

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

Syntax

function apply(callable $transform, int $value): int

Parameter callable prijíma Closure alebo iný volateľný tvar, napríklad dvojicu objekt a názov verejnej metódy. Typ neurčuje signatúru cieľa. Pri volaní musia argumenty zodpovedať. Vlastnosť možno deklarovať ako Closure, nie ako callable.

class Scale { public function twice(int $n): int { return $n * 2; } }
function apply(callable $transform, int $value): int { return $transform($value); }
echo json_encode([apply([new Scale(), 'twice'], 3), apply(fn(int $n): int => $n+1, 3)]);
[6,4]

Príklady

<?php
class Scale { public function twice(int $n): int { return $n * 2; } }
function apply(callable $transform, int $value): int { return $transform($value); }
echo json_encode([apply([new Scale(), 'twice'], 3), apply(fn(int $n): int => $n+1, 3)]);

Výsledok

[6,4]

Zdroje