Simple example of PHP closure definition and usage

不言
Release: 2023-03-23 17:22:02
Original
1490 people have browsed it

This article mainly introduces the definition and use of PHP closures. It has certain reference value. Now I share it with everyone. Friends in need can also refer to it.

The examples in this article describe the definition and use of PHP closures. use. Share it with everyone for your reference, the details are as follows:


<?php
function getClosure($i)
{
  $i = $i.&#39;-&#39;.date(&#39;H:i:s&#39;);
  return function ($param) use ($i) {
    echo "--- param: $param ---\n";
    echo "--- i: $i ---\n";
  };
}
$c = getClosure(123);
$i = 456;
$c(&#39;test&#39;);
sleep(3);
$c2 = getClosure(123);
$c2(&#39;test&#39;);
$c(&#39;test&#39;);
/*
output:
--- param: test ---
--- i: 123-21:36:52 ---
--- param: test ---
--- i: 123-21:36:55 ---
--- param: test ---
--- i: 123-21:36:52 ---
*/
Copy after login


Another example


$message = &#39;hello&#39;;
$example = function() use ($message){
 var_dump($message);
};
echo $example();
//输出hello
$message = &#39;world&#39;;
//输出hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候
echo $example();
//重置为hello
$message = &#39;hello&#39;;
//此处传引用
$example = function() use(&$message){
 var_dump($message);
};
echo $example();
//输出hello
$message = &#39;world&#39;;
echo $example();
//此处输出world
//闭包函数也用于正常的传值
$message = &#39;hello&#39;;
$example = function ($data) use ($message){
 return "{$data},{$message}";
};
echo $example(&#39;world&#39;);
//此处输出world,hello
Copy after login

Related recommendations:

Instructions for the practical application of php closure features

Detailed explanation of php closure function code examples

The above is the detailed content of Simple example of PHP closure definition and usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!