php类型提示:类似数据类型

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没有另外一些语言灵活,但是可以通过类型提示来实现类型;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值