php的類裡可以有兩個建構函式?

來源:互聯網
上載者:User
class ecs_error{    var $_message   = array();    var $_template  = '';    var $error_no   = 0;    /**     * 建構函式     *     * @access  public     * @param   string  $tpl     * @return  void     */    function __construct($tpl)    {        $this->ecs_error($tpl);    }    /**     * 建構函式     *     * @access  public     * @param   string  $tpl     * @return  void     */    function ecs_error($tpl)    {        $this->_template = $tpl;    }

已經有了一個__construct(), 還有一個跟類名同名的建構函式ecs_error();
為什麼要有兩個建構函式?是為了匹配不同的版本嗎?

回複內容:

class ecs_error{    var $_message   = array();    var $_template  = '';    var $error_no   = 0;    /**     * 建構函式     *     * @access  public     * @param   string  $tpl     * @return  void     */    function __construct($tpl)    {        $this->ecs_error($tpl);    }    /**     * 建構函式     *     * @access  public     * @param   string  $tpl     * @return  void     */    function ecs_error($tpl)    {        $this->_template = $tpl;    }

已經有了一個__construct(), 還有一個跟類名同名的建構函式ecs_error();
為什麼要有兩個建構函式?是為了匹配不同的版本嗎?

應該是的,PHP4 是用的同名函數做建構函式,而 PHP5 用的是 __construct,具體請參考:

http://php.net/manual/zh/language.oop5.decon.php
http://php.net/manual/zh/oop4.constructor.php

應該不是吧,裡面的語句都不一樣,至於為啥這麼寫就不知道了

php4 沿襲 C++ 以類名的同名函數作為建構函式
php5 新增了 __construct 作為建構函式

由於你的類屬性定義是 php4 風格的,所以可認為這個類是在 php4 基礎上的擴充
並非向下相容,而是畫蛇添足

這個是為了相容
在php4中建構函式採用與類同名的方式進行定義
在php5中建構函式採用__construct定義

在php4中不識別__construct,不影響程式正常運行
在php5中,當二者同時存在時,__construct優先

關於php的一些知識可以看下視頻教程的,很多應該都有講到
v8視頻 有很多編程方面的視頻教程 v8視頻

  • 聯繫我們

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