Pass Private PHP Methods as Callbacks Safely

An array such as [$this, "format"] remains a scope-dependent callable. If external code invokes it, a private or protected method may fail its visibility check. Create a Closure inside the class instead; the closure keeps the class scope in which it was created.

Last updated: October 28, 2026.

<?php
final class Formatter
{
    public function callback(): Closure
    {
        return $this->format(...);
        // Alternative: Closure::fromCallable([$this, 'format']);
    }

    private function format(string $value): string
    {
        return strtoupper(trim($value));
    }
}

$formatter = new Formatter();
$result = array_map($formatter->callback(), [' alpha ', ' beta ']);

print_r($result); // ALPHA, BETA

The public method deliberately exports a callable without making the underlying implementation method public. The consumer receives a normal Closure that it can store and invoke independently.

Understand when visibility is checked

The PHP callables documentation explains that string and array callables can depend on the scope where they are invoked. External callback consumers do not gain access to private methods merely because the array was assembled inside the class.

First-class callable syntax, shown as $this->format(...), creates a closure in the current class scope. Closure::fromCallable() provides the same useful conversion and is documented by PHP’s Closure reference. Create either form where the target method is visible.

Expose the smallest callback surface

Do not make an implementation method public solely to satisfy a callback API. A public factory method can return a narrow closure while the private method remains hidden. Alternatively, an invokable object with __invoke() works well when the callback needs dependencies or meaningful state.

Use is_callable() only as a validation aid; it evaluates callability from the current scope and magic methods can affect the result. Prefer a Closure property or parameter when stored callbacks must always be directly invokable. Continue with PHP function parameters and scope, understanding callback scheduling, and handling callback failures safely.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov