为什么以下代码在 php7 可以执行, php5.6 却不行?

2017-11-01 21:02:37 +08:00
 waibunleung
php 代码:
<?php
class User
{
public $username;

public function __construct(string $username)
{
$this->username = $username;
}
}

$users = [
new User('user 1'),
new User('user 2'),
new User('user 3'),
];

$usernames = array_column($users, 'username');
var_dump($usernames);

//在 php7 执行以上代码能得到想要的输出,
//但是在 php5.6 执行时先提示 Argument 1 passed to User::__construct() must be an instance of string, string given 的错误
//把构造方法的 string 去掉之后 输出的却是一个空数组
//所以很奇怪 php7 相较于 php5 来说内部究竟发生了什么变化致使 php7 能得到预想的输出呢?

望各位赐教...小弟刚转 php7
2229 次点击
所在节点    问与答
1 条回复
GooMS
2017-11-01 21:45:59 +08:00
类型约束

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/402745

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX