面向对象之类型提示
“参数默认情况下也可以包含任何类型的对象。这种灵活性有它的好处,但是在方法定义中可能出现一些问题,为了解决这个问题(没有强制要求参数类型),PHP5引入了类的类型提示(type hint)。要增加几个方法参数的类型提示,只需简单地将类名放在需要约束的方法参数之前”
class ShopProduct{
public $title;
public $productMainName;
public $productFirstName;
public $price;
function __construct( $title,$firstName,$mainName,$price ) {
$this->title = $title;
$this->productFirstName = $firstName;
$this->productMainName = $mainName;
$this->price = $price;
}
function getProduct(){
return "{$this->productFirstName}"."{$this->productMainName}"
}
}
class ShopProductWrite {
public function write ( $shopProduct ) {
$str = "{$shopProduct->title}: " .$shopProduct->getProduct()." ({$shopProduct->price})\n";
print $str;
}
}
操作这个类
$product = new shopProduct( "ai","pan","shi.com","20151207" );
$write = new shopProductWrite();
$write->write( $product );
//输出:aipanshi.com (20151207)
$product
作为一个对象的参数,但是在实际处理参数$shopProduct
之前不会知道具体是什么。为了解决这个问题(没有强制要求参数类型),PHP5引入了类的类型提示(type hint)。要增加几个方法参数 的类型提示,只需简单地将类名放在需要约束的方法参数之前。如下:
public function write ( ShopProduct $shopProduct ) {
//...
}
//数组提示
function setArray( array $storearray ) {
$this->array = $storearray;
}
在PHP5.1加入了对数组提示的支持,而后来的版本还新增对null默认值的参数提示,既可以指定参数为一个特定类型或null值。如下:
function setWrite( ObjectWrite $objwrite=null ) {
$this->write = $objwrite;
}