4) ★ Class Type Hints 類型指示
大家都知道,PHP是一種弱類型的語言。在使用變量前不需要定義,不需要聲明變量的數(shù)據(jù)類型。這在編程中帶來很多便利,但也帶了一些隱患,特別當(dāng)變量的類型變化時。在PHP5增加了類型指示,可以在執(zhí)行過程中自動對類方法的參數(shù)類型進(jìn)行判斷。這類似于Java2中的RTTI,配合reflection可以讓我們很好地控制對象。
<?php
interface
Foo
{
function
a
(
Foo $foo
);
}
interface
Bar
{
function
b
(
Bar $bar
);
}
class
FooBar
implements
Foo
,
Bar
{
function
a
(
Foo $foo
) {
// ...
}
function
b
(
Bar $bar
) {
// ...
}
}
$a
= new
FooBar
;
$b
= new
FooBar
;
$a
->
a
(
$b
);
$a
->
b
(
$b
);
?>
在強(qiáng)類型語言中,所有變量的類型將在編譯時進(jìn)行檢查,而在
PHP
中使用類型指示來對類型的檢查則發(fā)生在運(yùn)行時。如果類方法參數(shù)的類型不對,將會報(bào)出類似“
Fatal error: Argument 1 must implement interface Bar…”這樣的錯誤信息。
以下代碼:
<?php
function
foo
(
ClassName $object
) {
// ...
}
?>
相當(dāng)于:
<?php
function
foo
(
$object
) {
if (!(
$object
instanceof
ClassName
)) {
die(
"Argument 1 must be an instance of ClassName"
);
}
}
?>
5) ★ final final關(guān)鍵字
PHP5中新增加了final關(guān)鍵字,它可以加在類或類方法前。標(biāo)識為final的類方法,在子類中不能被覆寫。標(biāo)識為final的類,不能被繼承,而且其中的方法都默認(rèn)為final類型。
Final
方法:
<?php
class
Foo
{
final
function
bar
() {
// ...
}
}
?>
Final
類:
<?php
final class
Foo
{
// class definition
}
//
下面這一行是錯誤的
// class Bork extends Foo {}
?>
6) ★ Objects Cloning 對象復(fù)制
前面在內(nèi)存管理部份說過,PHP5中默認(rèn)通過引用傳遞對象。像使用$object2=$object1這樣的方法復(fù)制出的對象是相互關(guān)聯(lián)的。如果我們確實(shí)需要復(fù)制出一個值與原來相同的對象而希望目標(biāo)對象與源對象沒有關(guān)聯(lián)(像普通變量那樣通過值來傳遞),那么就需要使用clone關(guān)鍵字。如果還希望在復(fù)制的同時變動源對象中的某些部份,可以在類中定一個__clone()函數(shù),加入操作。
<?php
//
對象復(fù)制
class
MyCloneable
{
static
$id
=
0
;
function
MyCloneable
() {
$this
->
id
=
self
::
$id
++;
}
/*
function __clone() {
$this->address = "New York";
$this->id = self::$id++;
}
*/
}
$obj
= new
MyCloneable
();
$obj
->
name
=
"Hello"
;
$obj
->
address
=
"Tel-Aviv"
;
print
$obj
->
id
.
"\n"
;
$obj_cloned
= clone
$obj
;
print
$obj_cloned
->
id
.
"\n"
;
print
$obj_cloned
->
name
.
"\n"
;
print
$obj_cloned
->
address
.
"\n"
;
?>
以上代碼復(fù)制出一個完全相同的對象。
然后請把function __clone()這一個函數(shù)的注釋去掉,重新運(yùn)行程序。則會復(fù)制出一個基本相同,但部份屬性變動的對象。
8) ★ Class Constants 類常量
PHP5中可以使用const關(guān)鍵字來定義類常量。
<?php
class
Foo
{
const
constant
=
"constant"
;
}
echo
"Foo::constant = "
.
Foo
::
constant
.
"\n"
;
?>
11) ★__METHOD__ constant __METHOD__常量
魔術(shù)常量是一種PHP預(yù)定義常量,它的值可以是變化的,PHP中的其它已經(jīng)存在的魔術(shù)常量有__LINE__、__FILE__、__FUNCTION__、__CLASS__等。
<?php
class
Foo
{
function
show
() {
echo
__METHOD__
;
}
}
class
Bar
extends
Foo
{
}
Foo
::
show
();
// outputs Foo::show
Bar
::
show
();
// outputs Foo::show either since __METHOD__ is
// compile-time evaluated token
function
test
() {
echo
__METHOD__
;
}
test
();
// outputs test
?>