Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

__invoke

An object with a public `__invoke` method can be used as a callable.

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

Syntax

public function __invoke(int $value): int

An object with a public __invoke method can be used as a callable. Arguments, return values and type checks follow the method signature, and $this preserves the object’s state between calls. A plain object without this behavior cannot be called as a function. The example passes an invokable instance directly to array_map.

class Accumulator {
    private int $sum = 0;
    public function __invoke(int $value): int { return $this->sum += $value; }
}
$add = new Accumulator();
echo json_encode([is_callable($add), $add(2), array_map($add, [3, 1]), is_callable(new stdClass())]);
[true,2,[5,6],false]

Examples

<?php
class Accumulator {
    private int $sum = 0;
    public function __invoke(int $value): int { return $this->sum += $value; }
}
$add = new Accumulator();
echo json_encode([is_callable($add), $add(2), array_map($add, [3, 1]), is_callable(new stdClass())]);

Result

[true,2,[5,6],false]

Sources