PHP Function With Return Value In Hindi

📔 : PHP 🔗

 किसी भी function return statement यह  function का end  indicate करता है।  means function के अंदर जहां भी हम return statement लिखते हैं function वही तक execute  होता है , value return करने के बाद execution उसी line  से  start होता है जी line में हमने उसे call किया था।


हालाँकि PHP User Define Functions में return statement Optional होता है , आप चाहे तो function में value return करा सकते हैं और नहीं भी।

PHP Function With Return Value Syntax

function function_name()
{
  return value;
}

PHP Function With Return Value Example

File : return_fun.php

Copy Fullscreen Close Fullscreen
<?php
  function test()
  {
    return echo "Hello Test";
  }

  echo test();
?>
Output
Hello Test

Note - जैसा कि आप पिछले topic में पढ़ चुके हैं कि PHP में Function names A to Z के लिए case insensitive होते हैं means , example में define किये गए function को आप test(), Test() या tesT() से भी call करा सकते हैं।

PHP Function : Return Type Declaration

Older Versions में हम किसी भी तरह की value return करा सकते हैं। PHP 7 में function के लिए एक नया update आया return type declaration. means function define करते समय हम return type भी define करते हैं जो कि ensure करता है कि वह function सिर्फ define किये गए type की value ही return करेगा।

See Example

File : return_fun2.php

Copy Fullscreen Close Fullscreen
<?php
  function test1() : string
  {
    return "Hello Test";
  }

  echo Test1();
?>
Output
Hello Test

Example में आप देख सकते हैं कि किस तरह से function के लिए return type declare करते हैं।

PHP Function : Return Type With Strict Mode

अगर हम define किये गए type की value return नहीं करते हैं तो वह function कुछ भी return नहीं करता है , या हो सकता है कि Warning generate करे और अगर Strict Mode On हुई तो PHP Fatal Error Generate कर सकती है।

See Example

File : return_fun3.php

Copy Fullscreen Close Fullscreen
<?php
  declare(strict_types=1);
  function test1() : int
  {
    return "Hello Test";
  }

  echo Test1();
?>
Output
PHP Fatal error: Uncaught TypeError: Return value of test1() must be of the type integer, string returned in C:\xampp\htdocs\test\param_fun3.php:5

Explain : Example में function का return type integer define किया गया है जबकि function string value return कर रहा है , इसलिए fatal error generate हुई।

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