Description
From manual page: https://www.php.net/manual/en/language.types.callable.php
While debugging why a piece of code involving object instance callables acts as if it was never called, I have discovered a behavior that is only implied by the docs. It is best if this behavior is directly pointed out.
Consider:
class SignalListener {
public function __construct() {
pcntl_signal(SIGTERM, [$this, 'signalHandler']);
}
private function signalHandler() {
echo 'signal!';
}
}
Then:
$listener = new SignalListener();
posix_kill(getmypid(), SIGTERM);
One may expect that $listener->signalHandler()
is called since the callable might actually be referenced directly by the runtime somehow, so perhaps the PCNTL function in question might actually be able to call $listener->signalHandler()
. This misconception therefore prompts the following expected output:
signal!
...but actually, this triggers the following error:
Invalid callback SignalListener::signalHandler, cannot access private method SignalListener::signalHandler [...]
Currently, the docs mention that "accessing protected and private methods from within a class is allowed", but it does not mention what happens when protected/private methods are being passed as callables to outside a class, such as the PCNTL module functions that exists freely with no namespaces or classes.
It is best if the docs can explicitly mention that protected/private members inside a class are still not callable outside its own class even via the callables syntax.
It does not seem like this behavior will change, and this can be a gotcha moment for inexperienced devs, so this is worthy of being put into the official docs.