简体   繁体   中英

Does php have an equivalent of javascript arrow functions (=>)?

I know the => symbol is used when constructing arrays in php. But in javascript, you can use the symbol to shorten a function like this:

var materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]

where material would be the input of the function and material.length the return value.

Is there's an equivalent in php?

In php7.4 arrow functions are implemented according to this rfc https://wiki.php.net/rfc/arrow_functions_v2

Sample here: https://3v4l.org/ddooc , watch the results depending on php version.

$array = ['string1', 'longstring'];
print_r(array_map(fn($x) => strlen($x), $array));

In older versions of php you still have to use:

array_map( 
    function ($x) {
        return strlen($x);
    },
    $array
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM