【问题标题】:what does it mean by array $options = [] in method argument方法参数中的数组 $options = [] 是什么意思
【发布时间】:2017-11-14 06:26:56
【问题描述】:

我在网上找到了一个在方法参数中使用数组 $options = [] 的 php 类:

class TADFactory
{
    private $options;


    public function __construct(array $options = [])
    {
        $this->options  = $options;
    }

//some other methods here
}

在 page.php 文件中

$tad_factory = new TADFactory(['ip'=>'192.168.0.1']);
//some other stuffs here

但是在浏览器中执行page.php文件后,却显示:

Unexpected `[` in page.php file at line 1, expecting `)`....

但是根据php库文档,我必须通过这种方式在参数中使用多维数组。

我不明白 TADFactory 类参数中的 array $options = [] 是什么意思以及为什么会抛出错误?

【问题讨论】:

  • 你运行的是什么版本的 PHP?
  • array 是强制您传递数组的类型提示,= []$options 设置为空数组(默认)。
  • 这种短数组语法是在 PHP 5.4 中引入的。如果您运行的是旧版本,则需要将其更改为使用 array $options = array()$tad_factory = new TADFactory(array('ip'=>'192.168.0.1'));
  • 如果是这种情况,您将不得不更改 TADFactory(['ip'=>'192.168.0.1']); 以使用旧语法,并且可能还有很多“新”数组语法的其他用法。

标签: php class arguments


【解决方案1】:

那是default argument value。这是你如何声明一个参数是可选的,如果没有提供,它默认应该有什么值。

function add($x, $y = 5) {
    return $x + $y;
}

echo add(5, 10); // 15
echo add(7); // 12

至于数组注解,也就是type hint(也叫类型声明),意思是必须给函数传递一个数组,否则会报错。类型提示在动态语言中是相当复杂且必要的,但值得商榷。

function sum(array $nums) {
    return array_sum($nums);
}

echo sum([1, 2, 3]); // 6
echo sum(5); // throws an error

注意:如果您的默认参数值为 null,则只能将类型提示与默认参数值结合使用。

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2011-02-20
    • 2021-03-04
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多