細數php文法裡的那些“坑”

來源:互聯網
上載者:User

標籤:style   blog   color   java   使用   io   strong   for   

儘管PHP的文法已經很鬆散,寫起來很“爽”。但是對於像“我們”這種學過 Java、 C#的“完全物件導向程式員”來說,PHP程式設計語言裡,還是有一些的坑的。下面請讓我來盤點一下。

 

Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in......

  錯誤原因:在PHP文法中,聲明任何函數,函數名的前面需要 function 關鍵字。

<?php//錯誤碼如下class Test{  __construct(){    echo ‘I am construction!‘;      }    }

  正確樣本:每一次聲明函數(方法),都要寫上“function”這個關鍵字。無論您想聲明的是 __construct()這類魔術方法,還是自訂函數,都逃不出 function 的手掌心。

<?phpclass Test{  //正確代碼如下    function __construct(){        echo ‘I am construction!‘;    }}

 

 

Fatal error: Access to undeclared static property: ......

   錯誤原因:self::只能指向靜態屬性,而指向非靜態屬性只能用 $this->。

<?php//錯誤碼class Person{    function __construct($name){        self::$name = $name;    }    private $name;}$paul = new Person(‘paul‘);

  正確方法:self::指向靜態屬性,$this->指向非靜態屬性。

<?php//正確代碼 $thisclass Person{    function __construct($name){        $this->$name = $name;    }    private $name;}$paul = new Person(‘paul‘);

 

<?php//正確代碼 self::class Person{    function setBirthday($date){        self::$birthday = $date;    }    static private $birthday;}$paul = new Person();$paul->setBirthday(‘1990-01-01‘);

 

Fatal error: Cannot redeclare A::__construct() in......

  錯誤原因:PHP不支援函數重載

  解決方案:使用PHP內建函數 func_num_args() 、func_get_arg() 、func_get_args()來類比實現OOP的函數重載

<?phpclass Test{    function __construct(){        switch(func_num_args()){            case 0:                echo ‘no argument‘;            default:                echo ‘the number of arguments is ‘.func_num_args(). ‘<br />‘;                $argumentArray = func_get_args();                //遍曆方法一                foreach($argumentArray as $key => $value){                    echo ‘the No‘. $key. ‘ argument is ‘. $value. ‘<br />‘;                }                echo ‘<br />‘;                //遍曆方法二                for($i=0; $i<func_num_args(); $i++){                    echo ‘the No‘. $i. ‘ argument is ‘. func_get_arg($i). ‘<br />‘;                }        }        echo ‘<hr />‘;    }}new Test();new Test(1);new Test(1,2,3);

 

 

自動初始化對象

聯繫我們

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