Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

PHP Closure class

Giới thiệu

Hàm ẩn danh (anonymous function, còn gọi lambda) trả về đối tượng của lớp Closure. Lớp này có phương thức bổ sung cung cấp thêm kiểm soát cho hàm ẩn danh.

Cú pháp

Closure { private __construct ( void ) public static bind ( Closure $closure, object $newthis [, mixed $newscope = "static" ] ) : Closure public bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure public call ( object $newthis [, mixed $... ] ) : mixed public static fromCallable ( callable $callable ) : Closure }

Phương thức

  • Closure::__construct() - Chỉ để ngăn khởi tạo Closure. Đối tượng tạo bởi hàm ẩn danh.
  • Closure::bind() - Nhân bản closure với đối tượng và phạm vi class cụ thể. Phiên bản static của bindTo().
  • Closure::bindTo() - Nhân bản closure với đối tượng và phạm vi class mới. Tạo hàm ẩn danh mới cùng body và biến bound, nhưng đối tượng và phạm vi class khác.
  • Closure::call() - Tạm gán closure cho newthis và gọi với tham số cho trước.

Ví dụ Closure

<?php class A { public $nm; function __construct($x) { $this->nm = $x; } } // Dùng call method $hello = function() { return "Hello " . $this->nm; }; echo $hello->call(new A("Amar")) . "\n"; // Dùng bind method $sayhello = $hello->bindTo(new A("Amar"), 'A'); echo $sayhello(); ?>

Kết quả

Hello Amar Hello Amar