php中func_get_arg,func_get_args,func_num_args實現偽重載

來源:互聯網
上載者:User

偶爾在網上看到關於php的偽重載的問題,有點興趣便研究了一下。下面作者將說說php如何利用func_get_arg,func_get_args,func_num_args實現函數的偽重載問題。

首先說說方法重載的好處:

實現方法重載可以不用為了對不同的參數類型或參數個數,而寫多個函數。多個函數用同一個名字,但參數表,即參數的個數或(和)資料類型可以不同,調用的時候,雖然方法名字相同,但根據參數表可以自動調用對應的函數。如果我們使用reflector去查看微軟寫的.net的基底類別庫的話,我們可以發現他使用很多的方法重載,這樣我們在調用的時候,就不需要記那麼多的方法名稱,而是知道了方法的功能就可以直接的給他傳遞不同的參數,編譯器會明確的知道我們調用了哪一個方法。

但是在PHP中沒有函數重載這個概念,讓很多時候我們無法進行一些處理,甚至有時候不得不在函數後面定義好N個參數來解決相關問題,而php提供了幾個函數,比如:func_get_arg,func_get_args,func_num_args 卻可以直接解決相關問題。具體舉個範例程式碼如下:

 代碼如下 複製代碼
<?php
function  testOne($a) {
echo ('一個參數就這樣 ');
}
function testTwo($a, $b) {
 echo ('兩個參數的就這樣 ');
}
function testThree($a, $b, $c) {
 echo ('呵呵,這是三個參數的 ');
}
function test() {
 $argNum = func_num_args();
 // 這一段其實可以用 $_arg = func_get_args() 來獲得所有的參數,只是要用數組而已,不方便我下面的表達,呵呵
 for ($i = 0; $i < $argNum; $i++) {
  $_arg_{$i} = func_get_arg($i);
 }
 switch ($argNum) {
  case 1 :
   testOne($_arg_1);
  break ;
  case 2 :
   testTwo($_arg_1, $_arg_2);
  break ;
  case 3 :
   testThree($_arg_1, $_arg_2, $_arg_3);
  break ;
  default :
   echo (' 這是沒有參數的情況 ');
  break ;
 }
}
/**
 * 例子的實現
 */
test();
echo ('<br>');
test(1);
echo ('<br>');
test(1, 2);
echo ('<br>');
test(1, 2, 3);
// 這些只是在函數中的運用,其實最主要的還是在類中的運用
// 如果這些用到類裡面我就不需要擔心建構函式是否有幾個參數了,不是嗎?
// 類裡面的運用只舉一個簡單的例子
class test{
 var $a = 0;
 var $b = 0;
 function test() {
  $argNum = func_num_args();
  $_arg = func_get_args();
  switch ($argNum) {
   case 1 :
    $this->test1($_arg[0]);
   break ;
   case 2 :
    $this->test2($_arg[0], $_arg[1]);
   break;
   default :
    $this->a = 0;
    $this->b = 1;
   break;
  }
 }
 function test1($a) {
  $this->a = $a;
 }
 function test2($a, $b) {
  $this->a = $a;
  $this->b = $b ;
 }
}

友情提示

php的的func_num_args、func_get_arg和func_get_args都是返回函數實參相關的函數。

func_num_args:實參個數;

func_get_arg:返回某一個實參,必須事實參數組的索引;

func_get_args:返回實參數組;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.