PHP 7和严格的资源"类型

时间:2016-07-18 06:07:55

标签: php php-7

PHP 7是否支持严格的资源类型?如果是这样,怎么样?

例如:

<?php 
class appModel extends ActiveRecord\Model{
    public $app,$attr;
    public $db_config;

    function __construct(array $attributes=array(), $guard_attributes=true, $instantiating_via_find=false, $new_record=true){
        parent::__construct($attributes, $guard_attributes,$instantiating_via_find, $new_record);
    }


    function __call($key,$value){
        parent::__call($key,$value);
    }

    public function load($data){
        foreach($this->attributes as $attr=>$value){
            if(!isset($this->attr["".$attr])){
                //if(isset($data[$attr])) $this->attr["".$attr] =  $data[$attr];
                if(isset($data[$attr])) $this->attributes["".$attr] =  $data[$attr];
            }
        }
    }
}

以上将给出错误:

  

致命错误:未捕获的TypeError:传递给test()的参数1必须是资源的实例,给定资源

declare (strict_types=1); $ch = curl_init (); test ($ch); function test (resource $ch) { } 上的var_dump显示它是资源(4,curl),手册说$ch会返回资源。

是否可以严格键入curl_init ()功能以支持test()

2 个答案:

答案 0 :(得分:34)

PHP没有type hint for resources,因为

  

没有添加任何类型的资源提示,因为这会阻止资源从现有扩展的对象转移到某些已经完成的扩展(例如GMP)。

但是,您可以在函数/方法体中使用is_resource()来验证传递的参数并根据需要进行处理。可重用的版本将是这样的断言:

function assert_resource($resource)
{
    if (false === is_resource($resource)) {
        throw new InvalidArgumentException(
            sprintf(
                'Argument must be a valid resource type. %s given.',
                gettype($resource)
            )
        );
    }
}
然后你可以在代码中使用

function test($ch)
{
    assert_resource($ch);
    // do something with resource
}

答案 1 :(得分:7)

resource不是valid type所以根据旧的PHP / 5类型提示,它被假定为类名。但curl_init()不返回对象实例。

据我所知,没有办法指定资源。它可能不会那么有用,因为并非所有资源都相同:fopen()生成的资源对oci_parse()无用。

相关问题