Share your knowledge with other learners . . . Login Register

PHP Function Call By Value and Call By Reference

📔 : PHP 🔗

पिछले topics में हमें Parameterized  Function के बार में पढ़ा , ये functions call by value type के functions थे , means function call करते समय हम जो value pass करते हैं , और जब function run होता है तो इन values का बाहरी scope से कुछ मतलब नहीं होता वो function में as a local variable treat किये जाते हैं।


अगर आप function के अंदर उस value को manipulate भी करोगे तो उस variable की actual value ( जो कि function के बाहर है ) पर कोई फर्क नहीं पड़ता है।

PHP में ये दो तरह के function होते हैं -

1. Call By Value

2. Call By reference

PHP Difference Between Call By Value And Call By Reference

Call By Value और Call By Reference Functions में सबसे बड़ा difference भी यही है , Call By Value में हम सिर्फ value को accept करते हैं , इसलिए इस value को हम function के अंदर ही manipulate कर सकते हैं function के बाहर नहीं जबकि Call By Reference में हम function में value की जगह value का reference (जो कि & ampersand से access करते हैं ) use करते हैं।

PHP Function Call By Value

जैसा कि आपने ऊपर पढ़ा कि अभी तक हम जो functions define और use कर रहे थे ये Call By Value functions थे । जिसमे हम simply value को pass करते थे।

Example

File : call_by_value.php

CopyFullscreen Close Fullscreen
<?php
  $str = 'Hello';
  function test($str)
  {
    return $str.=' Welcome';
  }

  echo test($str)."<br>";
  echo $str;
?>
Output
Hello Welcome
Hello

Explain : Example में आप देख सकते हैं कि Function के अंदर value को manipulate किया गया है , but function call होने के बाद define किये गए external variable की value पर कोई असर नहीं पड़ा।


PHP Function Call By Reference

इस तरह के functions में function define करते समय parameter से पहले ampersand (&) का use करते हैं . Reference means variable content को different नाम के साथ access करना , हालाँकि यह Pointers की तरह नहीं है जैसे C में होता है। Learn more About Reference...

See Example

File : call_by_reference.php

Copy Fullscreen Close Fullscreen
<?php
  $str = 'Hello';
  function test(&$str)
  {
    return $str.=' Welcome';
  }

  echo test($str)."<br>";
  echo $str;
?>
Output
Hello Welcome
Hello Welcome

Explain :
Same Example में value की जगह variable से पहले value का reference (& ampersand)  use किया गया है , इसलिए function के अंदर value को modify करते ही उसकी actual value भी चेंज हो गयी।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers