Hàm is_callable

Hàm is_callable kiểm tra xem giá trị được truyền vào có thể gọi như một hàm hay không. Nó trả về true nếu giá trị là:

Cú pháp

phpis_callable(
  mixed $value,
  bool $syntax_only = false,
  string &$callable_name = null
): bool

Ví dụ

Kiểm tra hàm thông thường:

php<?php
  function test() {}
  $res = is_callable('test');
  var_dump($res);
?>

Kết quả thực thi mã:

phptrue

Ví dụ

Kiểm tra phương thức lớp:

php<?php
  class MyClass {
    public function method() {}
  }
  $obj = new MyClass();
  $res = is_callable([$obj, 'method']);
  var_dump($res);
?>

Kết quả thực thi mã:

phptrue

Ví dụ

Kiểm tra hàm không tồn tại:

php<?php
  $res = is_callable('non_existent_function');
  var_dump($res);
?>

Kết quả thực thi mã:

phpfalse

Ví dụ

Kiểm tra đối tượng có __invoke:

php<?php
  class Invokable {
    public function __invoke() {}
  }
  $obj = new Invokable();
  $res = is_callable($obj);
  var_dump($res);
?>

Kết quả thực thi mã:

phptrue

Xem thêm

  • hàm function_exists,
    hàm kiểm tra sự tồn tại của một hàm
  • hàm method_exists,
    hàm kiểm tra sự tồn tại của một phương thức lớp