PHP - 按值呼叫



預設情況下,PHP 使用“按值呼叫”機制將引數傳遞給函式。呼叫函式時,實際引數的值會被複制到函式定義的形式引數中。

在執行函式體期間,如果任何形式引數的值發生任何變化,都不會反映在實際引數中。

  • 實際引數 - 在函式呼叫中傳遞的引數。

  • 形式引數 - 在函式定義中宣告的引數。

示例

讓我們考慮一下下面程式碼中使用的函式:

<?php  
   function  change_name($nm) {
      echo "Initially the name is $nm \n";
      $nm = $nm."_new";
      echo "This function changes the name to $nm \n";
   }

   $name = "John";
   echo "My name is $name \n";
   change_name($name);
   echo "My name is still $name";
?>

它將產生以下輸出

My name is John
Initially the name is John
This function changes the name to John_new
My name is still John

在這個例子中,change_name() 函式將_new 附加到傳遞給它的字串引數。但是,傳遞給它的變數的值在函式執行後保持不變。

事實上,形式引數充當函式的區域性變數。這樣的變數只能在其初始化的作用域內訪問。對於一個函式,其由花括號“{ }”標記的主體是其作用域。此作用域內的任何變數都無法被外部程式碼訪問。因此,對任何區域性變數的操作都不會影響外部環境。

“按值呼叫”方法適用於使用傳遞給它的值的函式。它執行某些計算並返回結果,而無需更改傳遞給它的引數的值。

注意 - 任何執行公式型別計算的函式都是按值呼叫的示例。

示例

請看下面的例子:

<?php
   function addFunction($num1, $num2) {
      $sum = $num1 + $num2;
      return $sum;
   }
   $x = 10;
   $y = 20;
   $num = addFunction($x, $y);
   echo "Sum of the two numbers is : $num";
?>    

它將產生以下輸出

Sum of the two numbers is : 30  

示例

這是另一個透過按值傳遞引數來呼叫函式的示例。該函式將接收到的數字加 1,但這不會影響傳遞給它的變數。

<?php
   function increment($num) {
      echo "The initial value: $num \n";
      $num++;
      echo "This function increments the number by 1 to $num \n";
   }
   $x = 10;
   increment($x);
   echo "Number has not changed: $x";
?>

它將產生以下輸出

The initial value: 10
This function increments the number by 1 to 11
Number has not changed: 10

PHP 還支援在呼叫函式時傳遞變數的引用。我們將在下一章討論它。

廣告