PHP函数参数前的array关键字


array keyword before function parameters in PHP

我看到一个函数是这样声明的:

public static function factory($file=null, array $data=null, $auto_encode=null)

如果你想看到真正的类,请从github的fuelphp解析器包的一个分支中找到这个view.php类。

我的问题是,array关键字在array $data = null中意味着什么?

这是PHP5类型提示的一个例子。参数$data应该是一个数组。可以将方法参数提示为objectarray类型。如果是对象,可以将类名指定为hint关键字。

要求参数为数组。见http://php.net/manual/en/language.oop5.typehinting.php

如果我没记错的话,您可以在参数之前设置类名,以将变量类型限制为类的类型,但是,我不确定array在这里的使用是否有效。

编辑:显然我的PHP有点生疏了。根据http://php.net/manual/en/language.oop5.typehinting.php:

PHP 5引入了类型提示。函数现在能够强制参数为对象(通过在函数原型中指定类的名称)或数组(从PHP 5.1开始)。然而,如果NULL被用作默认参数值,它将被允许作为任何以后调用的参数。

例如:

<>之前 // An example class class MyClass { /** * A test function * * First parameter must be an object of type OtherClass */ public function test(OtherClass $otherclass) { echo $otherclass->var; } /** * Another test function * * First parameter must be an array */ public function test_array(array $input_array) { print_r($input_array); } } // Another example class class OtherClass { public $var = 'Hello World'; }