PHP中的类型约束介绍

来源:互联网 发布:.uno域名 编辑:程序博客网 时间:2024/06/05 03:21

PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型。

如下示例:

复制代码代码如下:

<?php
 
class Test
{
    public function test_array(array $arr)
    {
        print_r($arr);
    }
 
    public function test_class(Test1 $test1 = null)
    {
        print_r($test1);
    }
 
    public function test_callable(callable $callback, $data)
    {
        call_user_func($callback, $data);
    }
 
    public function test_interface(Traversable $iterator)
    {
        print_r(get_class($iterator));
    }
 
    public function test_class_with_null(Test1 $test1 = NULL)
    {
 
    }
}
 
class Test1{}
 
$test = new Test();
 
//函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。
 
$test->test_array(array(1));
$test->test_class(new Test1());
$test->test_callable('print_r', 1);
$test->test_interface(new ArrayObject(array()));
$test->test_class_with_null();

那么对于标量类型如何约束呢?

PECL扩展库中提供了SPL Types扩展实现interger、float、bool、enum、string类型约束。

复制代码代码如下:

$int  = new  SplInt ( 94 );
 
try {
     $int  =  'Try to cast a string value for fun' ;
} catch ( UnexpectedValueException $uve ) {
    echo  $uve -> getMessage () .  PHP_EOL ;
}
 
echo  $int  .  PHP_EOL ;
/*
运行结果:
Value not an integer
94
*/

SPL Types会降低一定的灵活性和性能,实际项目中三思而行。





PHP 5 可以使用类型约束。函数的参数可以指定只能为对象(在函数原型里面指定类的名字),php 5.1 之后也可以指定只能为数组。 注意,即使使用了类型约束,如果使用NULL作为参数的默认值,那么在调用函数的时候依然可以使用NULL作为实参。

Example #1 类型约束示例

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


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

//另外一个类
class OtherClass {
    public 
$var 'Hello World';
}
?>

函数调用的参数与定义的参数类型不一致时,会抛出一个致命错误。

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

// 致命错误:参数1必须是类OtherClass的一个对象
$myclass->test('hello');

// 致命错误:参数1必须为类OtherClass的一个实例
$foo = new stdClass;
$myclass->test($foo);

// 致命错误:参数1不能为null
$myclass->test(null);

// 正确:输出 Hello World 
$myclass->test($otherclass);

// 致命错误:参数1必须为数组
$myclass->test_array('a string');

// 正确:输出 数组
$myclass->test_array(array('a''b''c'));
?>

类型约束不只是用在类的成员函数里,也能使用在函数里。

<?php
// 如下面的类
class MyClass {
    public 
$var 'Hello World';
}

/**
 * 测试函数
 * 第一个参数必须是类MyClass的一个对象
 */
function MyFunction (MyClass $foo) {
    echo 
$foo->var;
}

// 正确
$myclass = new MyClass;
MyFunction($myclass);
?>

类型约束允许NULL值:

<?php

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

}

test(NULL);
test(new stdClass);

?>

类型约束只支持对象 和 数组(php 5.1之后)两种类型。而不支持整型 和 字符串类型。


0 0
原创粉丝点击