V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
waibunleung
V2EX  ›  问与答

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

  •  1
     
  •   waibunleung · 2017-11-01 21:02:37 +08:00 · 2223 次点击
    这是一个创建于 2360 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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
    1 条回复    2017-11-01 21:45:59 +08:00
    GooMS
        1
    GooMS  
       2017-11-01 21:45:59 +08:00 via Android
    类型约束
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4656 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 03:59 · PVG 11:59 · LAX 20:59 · JFK 23:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.