php物件導向精要 1

2022-09-15 07:21:09 字數 2450 閱讀 4661

1、靜態屬性與方法

每乙個類的例項擁有自己的屬性和方法,每乙個類也可以包含靜態屬性,靜態屬性不屬於類的任何例項,可以把靜態屬性理解成儲存在類中的全域性變數,可以在任何地方通過類名引用靜態屬性。

1

<?php

2class

myclass 7}

89$obj = new

myclass();

10echo

$obj->getvalue() . php_eol;11

12echo myclass::$a . php_eol

;13 ?>

2,靜態屬性的應用-----把乙個唯一的id傳遞到類的所有例項中

<?php

class

myclass

}$obj1 = new

myclass();

echo

$obj1->unique_id . php_eol

;

$obj2 = new

myclass();

echo

$obj2->unique_id . php_eol

;?>

3,靜態方法

1

<?php

2class

helloworld 78

static

function

printnewline()

11}

12 helloworld::sayhello();

13 helloworld::sayhello();

14 ?>

4,類的常量

>全域性常量用 define函式定義

>類的常量與靜態成員類似,他們屬於類本身,而不是類的例項

>類的常量對大小寫敏感

<?php

class

mycolorenumclass

}

mycolorenumclass::printcolor();

?>

5,物件轉殖

在php5中,物件賦值,其實是引用 , 如果需要拷貝物件,用轉殖關鍵字clone

<?php

class

myclass

$obj1 = new

myclass();

//$obj2 = $obj1;

$obj2 = clone

$obj1

;

$obj2->var = 2;

//使用$obj2 = $obj1, 下面輸出2

//使用$obj2 = clone $obj1, 下面輸出1

echo

$obj1->var . php_eol

;?>

6,多型

下面這個例項,如果想要再增加一種動物,那麼需要改動2處,需要增加動物類和方法,而且需要在printtherightsound方法中增加乙個elseif分支,這種設計對於**維護和分離非常不友好

<?php

class

cat }

class

dog }

function printtherightsound( $obj

)else

if ( $obj

instanceof dog )

else

echo

php_eol

; }

printtherightsound(

newcat() );

printtherightsound(

newdog() );

?>

我們可以用繼承的優勢,改造上面的缺點

1

<?php

2abstract

class

animal

5class cat extends

animal9}

10class dog extends

animal14}

15class chicken extends

animal 19}

2021

function printtherightsound( $obj

)else

27echo

php_eol;28

}2930 printtherightsound( new

cat() );

31 printtherightsound( new

dog() );

32 printtherightsound( new

chicken() );

33 ?>

這樣改造之後,printtherightsound就不需要改動,只需要新增對應的動物類和方法即可

PHP物件導向精要

1 使用extends實現繼承以及過載 魔術方法的含義 class b extends a 宣告的時候b裡可以沒有a裡的方法 呼叫的時候 b new b b a裡的方法 b a裡的屬性 1 b b裡的方法 b b裡的方法 如果 a new a 可以 a a裡的方法 a a裡的屬性 1 不可以 a b...

PHP物件導向精要

1 使用extends實現繼承以及過載 魔術方法的含義 class b extends a 宣告的時候b裡可以沒有a裡的方法 呼叫的時候 b new b b a裡的方法 b a裡的屬性 1 b b裡的方法 b b裡的方法 如果 a new a 可以 a a裡的方法 a a裡的屬性 1 不可以 a b...

php物件導向精要 3

1,final關鍵字定義的方法,不能被重寫 由於final修飾了show方法,子類中重寫show方法會報錯 class myclass class mytest extends myclass 2,final定義的class不能被繼承 final class myclass class mytest...