PHP物件導向學習筆記二

2021-10-10 21:09:10 字數 1241 閱讀 4921

上篇文章我記錄了一下關於php封裝的知識,這篇文章我就記錄一下關於php繼承的知識吧。

php中的繼承和嚴格意義上物件導向語言,比如:c#,是大同小異的。php中類的繼承需要使用extends這個關鍵字

<?php

class child extends father

?>

看,是不是很簡單,這樣child類就繼承了father類,子類中就把父類中不是用private修飾的屬性和方法繼承過來,當然,我們還可以在子類中定義新的方法和屬性,這樣做更有利於我們對**的重用。舉乙個關於繼承的小例子,如下:

<?php

class father

public function fmethod()

}class child extends father

public function cmethod

}$fobj = new father();

$cobj = new child();

$fobj->fmethod();

$cobj->cmethod();

$cobj->fmethod();

?>

以上**輸出的結果為:

1 2 1

<?php

final class father

?>

father就不能被其他的類繼承了。

<?php

class father

}?>

類中fmethod就不能被子類繼承了。

php只支援單重繼承,而不支援多重繼承,也就是說下面這樣的**是錯誤的

<?php

class father1

class father2

class child extends father1,father2

?>

要想實現多重繼承,我們可以用另一種方法,就是繼承多介面。

<?php

inte***ce ifather1

inte***ce ifather2

class child implements ifather1,ifather2

?>

我們看到在類繼承介面時使用的是implements這個關鍵字,這個地方需要大家注意一下,不用和類繼承類弄混了。

PHP物件導向學習二

類的繼承和應用 繼承關鍵字 extends class1 extends class2 extends class3 依次被繼承,class3擁有class1 class2所以功能和屬性,避免方法和屬性重名 class pc1 class pc2 extends pc1 class pc2擁有cla...

PHP學習筆記 物件導向

類的結構 class classname var attribute 新增屬性 function operation 宣告函式 建構函式 construct 析構函式 destruct 使用類的屬性 在乙個類中,可以訪問乙個特殊的指標 this。eg this attribute。在類的外部直接訪問...

PHP物件導向學習筆記

學習基於 細說php 類宣告 class 類名 類成員屬性 class person 成員方法 class person 例項化物件 person new person 訪問 引用名 成員屬性 成員方法 非靜態 物件成員方法引用成員屬性用 this class person 構造方法與析構方法 構造...