John Davidson

syntax - Is passing variables to php anonymus function without use legit?

0 comments
Message:


I just learned about php anonymous functions and found out that the following code is correct:


Example1:


//$mysqli = new mysqli(...)
(function($x, $y, $conn) {
echo $x, $y; //$x and $y are not visible outside
})(786, 333, $mysqli);

Over the internet I have found examples like


Example2:


$x = 786; $y = 333;
(function($x, $y) {
echo $x, $y;
})();

Or


Example3:


$x = 786; $y = 333;
(function() use($x, $y){
echo $x, $y;
})();

I couldn't find any php documentation or code on stackoverflow which suggest example1 is correct syntax. Please tell me with official reference if example1 like syntax is allowed in php.



My Answer:
In PHP, passing variables to an anonymous function without using them is not a common practice and may not be considered best practice. However, it is technically allowed and can be useful in certain situations.

In Example 1, the variables $x and $y are passed to the anonymous function but are not used within the function. This is allowed in PHP, but it may not be necessary or recommended unless there is a specific reason for doing so.

In Example 2, the variables $x and $y are defined outside the anonymous function and are not passed as arguments. This is also allowed in PHP, but again, it may not be necessary unless there is a specific reason for doing so.

In Example 3, the variables $x and $y are defined outside the anonymous function and are passed using the "use" keyword. This is a common practice in PHP when you want to use variables from the parent scope within the anonymous function.

Overall, while passing variables to an anonymous function without using them is technically allowed in PHP, it may not be considered best practice. It is important to consider the readability and maintainability of your code when using anonymous functions in PHP.

Rate this post

4 of 5 based on 7724 votes

Comments




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