PHP 11:函數

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

原文:PHP 11:函數

本文章介紹PHP的函數。
如何學習呢?可以從以下幾個方面考慮

  1.  函數是如何定義的?區分大小寫嗎?
  2. 函數的參數是如何定義的?
  3. 函數是否支援重載?
  4. 函數的傳回值是如何定義的。
  5. 函數有變數函數嗎?
如果把上面的問題搞清楚了,相信函數你也就掌握了。還是一個個看吧。
  1.  函數是如何定義的?區分大小寫嗎?
        首先函數對大小寫不敏感。但是還是建議你採用和函式宣告時的一樣。
        函數是如何定義的呢?文法可以為:
<?php
function func($arg_1, $arg_2, , $arg_n)
{
   
echo "Example function.\n";
   
return $retval;
}
?> 其實和其他語言差不多。不過函式宣告裡不需要顯式的說明傳回型別。和JavaScript差不多。
  那麼是不是和C語言一樣,函數先定義後使用呢?這個問題非常好。在PHP3中,確實需要這樣,但是後期版本則沒有限制了。
  由於PHP存在函數種的函數或條件函數,所以這2種情況下需要先定義後使用,要是沒有定義函數你卻使用了,系統會出問題的。函數中的函數倒是和Python有些類似。
 條件函數的例子可以是:
 1 <?php
 2  $isRequired=true;
 3  if($isRequired)
 4   {
 5       function func($op1,$op2)
 6        {
 7             return $op1+$op2;
 8       }
 9   }
10   if($isRequired)
11      echo "func(1,3)=".func(1,3);
12    
13    function helloWorld()
14    {
15         return "Hello,world";
16    }
17     echo ‘<br>Call function helloWorld():‘.helloWorld();
18 ?>輸出結果為:
func(1,3)=4
Call 
function helloWorld():Hello,world函數中的函數可以是:
 1 <?php
 2 function func()
 3 {
 4   function subfunc()
 5   {
 6    echo "I don‘t exist until func() is called.\n";
 7    echo "I have alrady made ";
 8   }
 9 }
10 
11 /* We can‘t call subfunc() yet
12    since it doesn‘t exist. */
13 
14 func();
15 
16 /* Now we can call subfunc(),
17    func()‘s processesing has
18    made it accessable. */
19 
20 subfunc();
21 
22 ?>  輸出結果是:
I don‘t exist until func() is called. I have alrady made 
2. 函數的參數是如何定義的?

    和通常使用的函數參數一樣,參數列表用逗號分隔。那麼參數是按值傳遞還是按引用傳遞呢?答案是值傳遞。如何按引用傳遞呢?其實和C++裡一樣,在參數前使用&符號。
   那麼如何設定預設的參數值呢?這個和C++一樣,在參數列表裡直接寫上就行了。例如:
<?php
function MakeComputerBrand($brand = "IBM")
{
   
return "Making ".$brand." computer now.<br>";
}
echo MakeComputerBrand();
echo MakeComputerBrand("DELL");
echo MakeComputerBrand("HP");
echo MakeComputerBrand("Lenevo");
?> 輸出的結果是:
Making IBM computer now.
Making DELL computer now
.
Making HP computer now
.
Making Lenevo computer now
.
3. 函數是否支援重載?

   不支援。

4 .函數的傳回值是如何定義的
。
   如果單獨返回一個值或不傳回值,和普通語言一樣,return就可以。但是若返回多個值,一種方法是返回一個數組。例如:
<?php
function small_numbers()
{
   
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?> 
5. 函數有變數函數嗎?

  有,和可變變數一樣。

PHP 11:函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.