Skip to content

PHP

closure=unanimous function

Author
siwon
Date
2023-08-30 15:34
Views
1305

Closures have been introduced in PHP 5.3 and their most important use is for callback functions. Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk(). By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.

  
    <?php

$array = array('Ruby', 'PHP', 'JavaScript', 'HTML');

array_walk($array, function(&$v, $k) {

$v = $v . ' - Programming Language';

});

print_r($array);



Assigning a closure as the value of a variable

You can define a closure as the value of a variable with a normal assignment. For example, the snippet below will print out 'I am a closure'.

  
    <?php

$var = function() {

return 'I am a ' . func_get_arg(0);

};

print_r($var('Closure'));



Don't forget to end the assignment with a semicolon just like you would do with any variable definition ... I always forget so I thought it would help if I mentioned this :).

Be careful with the scope

One of the most confusing aspects for these anonymous functions in PHP is related to how closures can make use of variables from their immediate parent scope (not necessarily the global scope). This is done with the use language construct so that the syntax looks like this: function() use ($variable) { /* code */ }.

In the example below, the closure will use / inherit the value of $param from its parent scope which is the scope of the sayHello() function, NOT the global scope and therefor the script will output Hi, I am Michael!.

  
    <?php

$param = 'John!';



function sayHello()

{

$param = 'Michael!';

$func = function() use ($param)

{

echo 'Hi, I am ' . $param;

};

$func();

}



sayHello();



If we were to modify the value of $param inside the closure this would not affect it's value inside the parent scope unless we would 'use a reference'. In the two examples below, one with $param as a reference and one as a normal (copied) variable the results are different.

This prints 'I am Michael!' because $param is not modified in its parent scope. In other words, the only place where $param='Dave!' is inside the closure.

  
    <?php

$param = 'John!';



function sayHello()

{

$param = 'Michael!';

$func = function() use ($param)

{

$param = 'Dave!';

};

$func();

echo 'I am ' . $param; // prints I am Michael!

}

sayHello();



The code below will print 'I am Dave!' because $param is 'used' as a reference.

  
    <?php

$param = 'John!';



function sayHello()

{

$param = 'Michael!';

$func = function() use (&$param)

{

$param = 'Dave!';

};

$func();

echo 'I am ' . $param; // prints I am Dave!

}

sayHello();



Update: January 7th 2020 - Arrow functions starting with PHP 7.4

Starting with version 7.4 PHP has the ability to interpret "arrow functions". Besides the obvious advatage of being shorter and more readable than classic anonymous functions, arrow functions can access variables from the parent scope through a technique called "implicit by-value scope binding"

Below there's a comparison between how a clasic closure behaves compared with a short closure.

  
        <?php

//classic closure

$n = "Mike";

$calc = function() {

return "Hello " . $n;

}

$calc(); // undefined variable $n

?>


<?php

//short closure

$calc = fn() => "Hello " . $n;

$calc(); //returns Hello Mike

?>




A few gotchas:

Arrow functions can only have one expression - the return statement (as opposed to JavaScript)

The outer scope variables are accessible by value only so there's no way of modify them

A few gotchas:

Arrow functions can only have one expression - the return statement (as opposed to JavaScript)

The outer scope variables are accessible by value only so there's no way of modify them

Total 0

Total 45
Number Title Author Date Votes Views
40
php formatter
siwon | 2024.11.26 | Votes -1 | Views 1319
siwon 2024.11.26 -1 1319
39
html center 중앙정렬 tailwind
siwon | 2024.07.27 | Votes 0 | Views 1639
siwon 2024.07.27 0 1639
38
dropdown menu alpinejs 사용 버전
siwon | 2024.04.30 | Votes 0 | Views 1564
siwon 2024.04.30 0 1564
37
dropdown menu 간단 버전
siwon | 2024.04.30 | Votes 0 | Views 1522
siwon 2024.04.30 0 1522
36
The Standard PHP Library (SPL) is a collection of classes and interfaces that provide core functionality to PHP developers.
siwon | 2023.10.24 | Votes 0 | Views 2201
siwon 2023.10.24 0 2201
35
session 과 쿠키
siwon | 2023.10.24 | Votes 0 | Views 1461
siwon 2023.10.24 0 1461
34
Late Static Binding (LSB):메서드 내부에서 현재 클래스의 정적 메서드 또는 프로퍼티를 호출할 때 사용
siwon | 2023.10.24 | Votes 0 | Views 1285
siwon 2023.10.24 0 1285
33
PHP 예외 처리(Exception Handling)
siwon | 2023.10.10 | Votes 0 | Views 1605
siwon 2023.10.10 0 1605
32
php exception
siwon | 2023.10.10 | Votes 0 | Views 1802
siwon 2023.10.10 0 1802
31
예외(Exception)를 처리하기 위해 try...catch 블록을 사용하는 방법
siwon | 2023.10.10 | Votes 0 | Views 1339
siwon 2023.10.10 0 1339
30
Preserving Parent Class Functionality in overriding
siwon | 2023.09.26 | Votes 0 | Views 1173
siwon 2023.09.26 0 1173
29
oop 세부항목
siwon | 2023.09.26 | Votes 0 | Views 1190
siwon 2023.09.26 0 1190
28
method chaining
siwon | 2023.09.25 | Votes 0 | Views 1419
siwon 2023.09.25 0 1419
27
interface implements
siwon | 2023.09.19 | Votes 0 | Views 1242
siwon 2023.09.19 0 1242
Re:interface implements
siwon | 2023.10.24 | Votes 0 | Views 1049
siwon 2023.10.24 0 1049
26
abstract class : 부모 class로 사용되며 자식(extends 한)에게 abstract method를 강제함(그들만의 방식으로)
siwon | 2023.09.19 | Votes 0 | Views 1136
siwon 2023.09.19 0 1136
25
isset() / unset()
siwon | 2023.09.18 | Votes 0 | Views 1314
siwon 2023.09.18 0 1314
24
magic methods-어떤 상황이 되면 call 하지 않아도 자동으로 실행되는 메소드
siwon | 2023.09.18 | Votes 0 | Views 1321
siwon 2023.09.18 0 1321
23
MD(markdown) file
siwon | 2023.09.12 | Votes 0 | Views 1239
siwon 2023.09.12 0 1239
22
usort
siwon | 2023.08.30 | Votes 0 | Views 1277
siwon 2023.08.30 0 1277
21
closure=unanimous function
siwon | 2023.08.30 | Votes 0 | Views 1305
siwon 2023.08.30 0 1305
php 7.4에서 추가 화살표 함수 fn()=>
siwon | 2023.10.24 | Votes 0 | Views 3970
siwon 2023.10.24 0 3970
20
reference variable &
siwon | 2023.08.29 | Votes 0 | Views 1296
siwon 2023.08.29 0 1296
참조(reference)한 original variable의 값을 바꿔버리기 때문에 조심해서 써야함
siwon | 2023.08.30 | Votes 0 | Views 1227
siwon 2023.08.30 0 1227
19
PHP 변수 : 스칼라(Scalar), 복합(Composite), 그리고 리소스(Resource)
siwon | 2023.08.22 | Votes 0 | Views 1376
siwon 2023.08.22 0 1376
18
if : vs {}
siwon | 2023.08.22 | Votes 0 | Views 1120
siwon 2023.08.22 0 1120
17
null coalescing operator
siwon | 2023.08.18 | Votes 0 | Views 1467
siwon 2023.08.18 0 1467
16
arrary functions
siwon | 2023.08.18 | Votes 0 | Views 1281
siwon 2023.08.18 0 1281