Skip to content

Instantly share code, notes, and snippets.

@yceruto
Last active September 17, 2024 05:00
Show Gist options
  • Save yceruto/b1a4e9ee6aa53f9aa21b41d463992d58 to your computer and use it in GitHub Desktop.
Save yceruto/b1a4e9ee6aa53f9aa21b41d463992d58 to your computer and use it in GitHub Desktop.
PHP Callables Examples
<?php
/*
* Functions without a name, created using the `function` keyword without a name or using the `fn` syntax.
*/
$func = fn (string $v): int => strlen($v);
var_dump(
is_callable($func),
is_callable($func(...)),
);
// https://3v4l.org/BOua9
<?php
/*
* PHP’s internal functions like `strlen()` or `strtolower()`.
*/
var_dump(
is_callable('strlen'),
is_callable(strlen(...)),
);
// https://3v4l.org/PnFL3
<?php
/*
* Objects that implement the `__invoke()` magic method, allowing them to be called as functions.
*/
class Foo
{
public function __invoke()
{
}
}
$foo = new Foo();
var_dump(
is_callable($foo),
is_callable([$foo, '__invoke']),
is_callable($foo(...)),
);
// https://3v4l.org/fBKu3
<?php
/*
* Methods within a class, which can be static or instance methods.
*/
class Foo
{
public function ping()
{
}
public static function pong()
{
}
}
$foo = new Foo();
var_dump(
is_callable([$foo, 'ping']),
is_callable($foo->ping(...)),
is_callable('Foo::pong'),
is_callable([Foo::class, 'pong']),
is_callable(Foo::pong(...)),
);
// https://3v4l.org/MdJDLm
<?php
/*
* Regular functions defined using the `function` keyword.
*/
function foo(): string
{
return 'bar';
}
var_dump(
is_callable('foo'),
is_callable(foo(...)),
);
// https://3v4l.org/tlWtD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment