標籤: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);
自動初始化對象