John Davidson

php - Static anonymous function vs normal anonymous function

0 comments
Message:


What is the difference between the following two anonymous functions? Static does not seem to do what I initially thought (which is executing it only once like rust constant functions).


$func1 = function () {
return true;
}

$func2 = static function () {
return true
}


My Answer:
The difference between the two anonymous functions is that the first one is a normal anonymous function, while the second one is a static anonymous function.

In PHP, static functions are used to define functions within a class that can be called without instantiating an object of that class. However, in the context of anonymous functions, the `static` keyword does not have the same meaning as it does in class methods.

In the case of the second anonymous function `$func2 = static function () { return true; }`, the `static` keyword is used to declare the function as static within the current scope. This means that the function will retain its state between calls and will not be redefined if the enclosing scope is re-executed.

In contrast, the first anonymous function `$func1 = function () { return true; }` is a normal anonymous function that does not have the `static` keyword. This function will be redefined every time the enclosing scope is executed.

Therefore, the main difference between the two anonymous functions is that the static anonymous function will retain its state between calls, while the normal anonymous function will be redefined each time it is called.

Rate this post

5 of 5 based on 4193 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us