OOP和設計模式中抽象有很多的重要的結構要素,其中一個就是指定數據類型的爲接口而不是一個具體實現,這說明對數據的引用要通過父類完成,這通常是一個接口或抽象類。
提供類型提示的基本格式如下:
function doWork(TypeHint $someVar)
類型提示必須是類或者接口的名字。在設計模式中,更傾向於使用抽象類或者接口,因爲他不會綁定一個具體實現的類型,而是限制了結構。
實例(一個接口文件,兩個實現接口類文件,一個類【四個文件】)
接口文件:IProduct.php
//提供類型提示的基本格式如下:
//function doWork(TypeHint $someVar)
interface IProduct
{
function apples();
function oranges();
}
實現接口文件1:FruitStore.php
<?php
include_once('IProduct.php');
Class FruitStore implements IProduct
{
public function apples()
{
// TODO: Implement apples() method.
return "FruitStore sez--we have apples.<br/>";
}
public function oranges()
{
// TODO: Implement oranges() method.
return "FruitStore sez--we have no citrus fruit.<br/>";
}
}
實現接口文件2:CitrusStore.php
<?php
include_once('IProduct.php');
Class CitrusStore implements IProduct
{
public function apples()
{
// TODO: Implement apples() method.
return "CitrusStore sez--we do not sell apples.<br/>";
}
public function oranges()
{
// TODO: Implement oranges() method.
return "CitrusStore sez--we have citrus fruit.<br/>";
}
}
有類型提示的對象文件 userProduct.php
<?php
//有類型提示的對象
include_once('CitrusStore.php');
include_once ('FruitStore.php');
Class Userproduct
{
public function __construct()
{
$appleSauce = new FruitStore();
$orangeJuice = new CitrusStore();
$this->dointerface($appleSauce);
$this->dointerface($orangeJuice);
}
//IProduce 在 dointerface是類型提示
function dointerface(IProduct $product)
{
echo $product->apples();
echo $product->oranges();
}
}
$woker = new Userproduct();
測試userProduct類時,會顯示:
瀏覽器上顯示的是對IProduct接口的不同實現。需要知道的是在dointerface()中,類型提示(type hint)IProduct能夠識別實現IProduct的兩個類。換句話說並不是把他們分別識別爲一個FruitStore的實例和一個CitrusStore的一個實例,而是識別他們共同的接口IProduct
注意:強制數據類型可以確保倘若給定方法中使用了代碼提示,那麼其中使用的對象(類中)必然有給定的接口。另外如果把一個接口作爲代碼提示,綁定會更寬鬆;他會綁定到接口而不是綁定到一個特定的實現。隨着程序變得越來越大,只要遵循接口,就可以做任何改變而不會對程序造成破壞。不僅如此,所做的修改也不會去具體實現糾纏不清。
不能使用標量類型(如string或int)作爲代碼提示,可以使用數組、接口(上面的例子是通過接口)和類作爲代碼提示;雖然php沒有另外一些語言靈活,但是可以通過類型提示來實現類型;