面向对象(七)类型约束

一、类型约束

PHP 5 可以使用类型约束。函数的参数可以指定必须为对象(在函数原型里面指定类的名字),接口,数组(PHP 5.1 起)或者 callable(PHP 5.4 起)。不过如果使用 NULL 作为参数的默认值,那么在调用函数的时候依然可以使用 NULL 作为实参。

如果一个类或接口指定了类型约束,则其所有的子类或实现也都如此。

类型约束不能用于标量类型如 int 或 stringTraits 也不允许。

//如下面的类
class MyClass
{
    /**
     * 第一个参数必须为 OtherClass 类的一个对象
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }

    /**
     * 第一个参数必须为数组 
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }

    /**
     * 第一个参数必须为递归类型
     */
    public function test_interface(Traversable $iterator) {
        echo get_class($iterator);
    }
    
    /**
     * 第一个参数必须为回调类型
     */
    public function test_callable(callable $callback, $data) {
        call_user_func($callback, $data);
    }
}

// OtherClass 类定义
class OtherClass {
    public $var = 'Hello World';
}

// 两个类的对象
$myclass = new MyClass;
$otherclass = new OtherClass;

//第一个参数必须是 OtherClass 类的一个对象
$myclass->test($otherclass);//Hello World

//第一个参数必须为数组
$myclass->test_array(array('a', 'b', 'c'));

// 参数要实现接口Traversable
$myclass->test_interface(new ArrayObject());//ArrayObject

// 正确:输出 int(1)
$myclass->test_callable('var_dump', 1);

类型约束不只是用在类的成员函数里,也能使用在函数里,允许 NULL 值

/* 接受 NULL 值 */
function test(stdClass $obj = NULL) {
	
}

test(NULL);
test(new stdClass);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值