PHP Arrow Functions In Hindi

📔 : PHP 🔗

PHP में Arrow Functions PHP version  7.4  में introduce किये गए थे। Anonymous Functions और  Arrow Functions दोनों ही functions को Closure Class implement करके बनाया गया है।  Arrow Functions भी same functionalities support करता है जो कि Anonymous Functions करता है , सिर्फ एक difference कि , Arrow Functions में external variables के लिए हमें use keyword का use नहीं करना पड़ता है।  ये variables हम directly access कर सकते हैं।

PHP Arrow Function Syntax

$x = x()=>value;

Note - Arrow Functions पढ़ने से पहले यह check कर लें कि आपका PHP Version 7 . 4 या इससे ज्यादा है , otherwise fatal error generate होगी।

PHP Arrow Function Example

File : arrow_fun.php

Copy Fullscreen Close Fullscreen
<?php
  $y = 1;
  $fn1 = fn($x) => $x+$y;
  echo $fn1(10);
?>
Output
11

Example में आप देख External Variables को function के अंदर easily access कर सकते हैं।

Simply Arrow ( => ) के बाद जो भी हम value लिखते हैं Arrow Function वो return कर देता है। हालाँकि इसके लिए हमें return statement लिखने की जरूरत नहीं पड़ती है।

What can we do with Arrow Function ?

Anonymous Functions और  Normal Functions की तरह ही Arrow Functions में भी हम Normal Variables , Variable reference , defining variable type , declare function return type , default parameter , optional parameter , variable length arguments etc... भी आसानी से use कर सकते हैं।

See Example

File : arrow_fun2.php

Copy Fullscreen Close Fullscreen
<?php
  /* we can define parameters with their types */
  $example = fn(array $var) => print_r($var);
  
  /* we can declare retrun type also */
  $example =  fn(): int => $x;
  
  /* we can set default parameters */
  $example =  fn($x = 42) => $x;
  
  /* we can pass variable reference */
  $example = fn(&$x) => $x;
  
  /* yes , we can handle variable length arguments */
  $example = fn($x, ...$rest) => $rest;
?>

What Does Arrow Function ?

1. callback function की तुलना में Arrow Function short होते हैं , जिससे performance fast और execution time कम हो जाता है।

2. External Variables ( जो कि function के बाहर define किये गए हैं ) को access करने के लिए use keyword नहीं use करना पड़ता है।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers