'ใช้' คีย์เวิร์ดสามารถใช้ผูกตัวแปรเข้ากับขอบเขตของฟังก์ชันเฉพาะได้
ใช้คีย์เวิร์ดเพื่อผูกตัวแปรเข้ากับขอบเขตของฟังก์ชัน -
ตัวอย่าง
<?php
$message = 'hello there';
$example = function () {
var_dump($message);
};
$example();
$example = function () use ($message) { // Inherit $message
var_dump($message);
};
$example();
// Inherited variable's value is from when the function is defined, not when called
$message = 'Inherited value';
$example();
$message = 'reset to hello'; //message is reset
$example = function () use (&$message) { // Inherit by-reference
var_dump($message);
};
$example();
// The changed value in the parent scope
// is reflected inside the function call
$message = 'change reflected in parent scope';
$example();
$example("hello message");
?> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
NULL string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "change reflected in parent scope" string(32) "change reflected in parent scope"
ในขั้นต้น ฟังก์ชัน 'ตัวอย่าง' จะถูกเรียกก่อน ครั้งที่สอง $message สืบทอดมา และค่าของมันจะเปลี่ยนไปเมื่อฟังก์ชันถูกกำหนด ค่าของ $message ถูกรีเซ็ตและสืบทอดอีกครั้ง เนื่องจากค่ามีการเปลี่ยนแปลงในขอบเขตรูท/พาเรนต์ การเปลี่ยนแปลงจึงสะท้อนให้เห็นเมื่อมีการเรียกใช้ฟังก์ชัน