After complaining about the tumultuous task of writing the keyword function
over and over, I asked someone about an easier way. The person said that PHP is going to have arrow function syntax similar to es6.
const foo = (x, y) => { return x + y; };
As I continued to look into this, I have not been able to find many examples online.
Can someone of the right caliber please expound upon this?
At this point, I am also really interested in how this would fit into the OOP aspect of PHP.
Arrow Function Syntax The syntax of the arrow function is: let myFunction = (arg1, arg2, ...argN) => { statement(s) } Here, myFunction is the name of the function. arg1, arg2, ... argN are the function arguments.
Arrow functions are introduced as an update in the PHP version 7.4. Arrow functions are supposed to be a more concise version of anonymous functions. Arrow functions can be seen as shorthand functions that automatically inherit the parent scope's variables.
The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.
Arrow functions aren't suitable for call , apply and bind methods, which generally rely on establishing a scope. Arrow functions cannot be used as constructors. Arrow functions cannot use yield , within its body.
Original answer from February 2018:
This appears to be the syntax described in https://wiki.php.net/rfc/arrow_functions. It does have an experimental implementation.
In the arrow functions proposal, it is mentioned that it's an alternative to the "short closures" proposal, https://wiki.php.net/rfc/short_closures
As of February 2018, the current versions of PHP are 7.1.4 / 7.2.2.
I can't find any confirmation that either proposal has been approved. The former is in the "Under Discussion" state, the latter is "Declined / Withdrawn in favor of http://wiki.php.net/rfc/arrow_functions". I think it's too soon to know whether it will be adopted in any future version of PHP.
Update December 2019:
The feature has been released in PHP 7.4, according to https://www.php.net/manual/en/migration74.new-features.php
Arrow functions provide a shorthand syntax for defining functions with implicit by-value scope binding.
<?php $factor = 10; $nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
But the usage has not been updated yet in the PHP manual page about Anonymous Functions
Here's a blog going into detail: https://stitcher.io/blog/short-closures-in-php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With