php函數重載的替代方法--偽重載詳解_php執行個體

來源:互聯網
上載者:User

函數重載的替代方法-偽重載,下面看一個具體的執行個體代碼。

<? php//函數重載的替代方法-偽重載////確實,在PHP中沒有函數重載這個概念,讓很多時候我們無法進行一些處理,甚至有時候不得不在函數後面定義好N個參數//在看到了func_get_arg,func_get_args,func_num_args,這三個函數的時候,你們是不是想起了什嗎?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 ( ' ' );test( 1 );echo ( ' ' );test( 1 , 2 );echo ( ' ' );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 ; }}?>

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

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