Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP Closure Class

บทนำ

Anonymous functions (หรือเรียกว่า lambda) คืนค่า object ของคลาส Closure คลาสนี้มีเมธอดเพิ่มเติมที่ให้การควบคุม anonymous functions เพิ่มเติม

ไวยากรณ์

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 }

เมธอด

private Closure::__construct ( void ) - เมธอดนี้มีอยู่เพื่อห้ามสร้าง instance ของ Closure class โดยตรง Object ของคลาสนี้ถูกสร้างโดย anonymous function

public static Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) - Closure - Duplicate closure พร้อม bound object และ class scope ที่กำหนด นี่คือ static version ของ Closure::bindTo()

public Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] ) - Closure - Duplicate closure พร้อม bound object ใหม่และ class scope สร้างและคืนค่า anonymous function ใหม่ที่มี body และ bound variables เดียวกัน แต่มี object ต่างกันและ class scope ใหม่

public Closure::call ( object $newthis [, mixed $... ] ) - mixed - ผูก closure กับ newthis ชั่วคราว และเรียกมันพร้อมพารามิเตอร์ที่ให้มา

Closure Example

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

ผลลัพธ์

โปรแกรมข้างต้นแสดงผลลัพธ์ดังนี้

Hello Amar Hello Amar