PHP中的java形式重載

來源:互聯網
上載者:User
PHP中的java方式重載

有的時候,能夠調用可變參數的同一個方法會非常方便。PHP能夠定義帶預設值的選擇性參數使這一做法成為可能。

可以在php5中用__call()實現這種方法重載。下面來看一個樣本。假設要用重載行為,那麼要將其放到抽象父類中。

abstract class OverloadableObject{ function __call($name, $args){ $method = $name."_".count($args); if(!method_exists($this,$method)){ throw new Exception("Call to undefined method".get_class($this)."::$method"); } return call_user_func_array(array($this,$method),$args); }}
這個類方法的主要行為都在 $method = $name."_".count($args); 顯示一行代碼中定義了。如果調用未定義方法,__call()方法會產生一個新方法,其名稱由原始方法和參數個數構成,用底線分開。然後用新產生的方法名調用改方法,將原來的參數也一起傳遞過去。

現在,如果要使用一個名為multiply的重載方法,可以使用兩個或三個參數來調用它,並在每種情況下進行相應操作,可以分別用兩個方法:multiply_2和multiply_3

class Multiplier extends OverloadableObject{ function multiply_2($one,$two){ return $one*$two; } function multiply_3($one,$two,$three){ return $one*$two*$three; }}為了使用這段代碼,只調用帶有兩個或三個參數的multiply方法。

$multi = new Multiplier;

echo $multi->multiply(5,6)."\n";

echo $multi->multiply(5,6,7)."\n";

?

  • 聯繫我們

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