V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
waibunleung
V2EX  ›  程序员

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

  •  
  •   waibunleung · 2017-11-01 21:33:29 +08:00 · 3712 次点击
    这是一个创建于 2357 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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
    12 条回复    2017-11-02 10:01:11 +08:00
    carlclone
        1
    carlclone  
       2017-11-01 21:38:39 +08:00 via Android
    你是来黑 PHP 的吧
    wdlth
        2
    wdlth  
       2017-11-01 21:45:43 +08:00
    Changelog ¶

    Version Description
    7.0.0 Added the ability for the input parameter to be an array of objects.

    文档里面不是已经说了么……
    ruchee
        3
    ruchee  
       2017-11-01 21:49:46 +08:00
    http://cn.php.net/manual/zh/migration70.new-features.php
    http://cn.php.net/manual/zh/function.array-column.php

    对应上面两个文档说明,原因分别是:
    1. 类型声明 7.0 才支持
    2. array_column 函数从 7.0 开始才支持对象数组
    kendetrics
        4
    kendetrics  
       2017-11-01 21:55:15 +08:00
    用了 7 独有的特性呗,多简单的事。。
    lepig
        5
    lepig  
       2017-11-01 21:55:23 +08:00
    楼主的例子不就是 Example #3 拷贝过来的么

    完全不看文档。
    oswuhan
        6
    oswuhan  
       2017-11-01 22:04:52 +08:00
    这种水分大的问题,直接去 https://segmentfault.com/上问,同道中人很多
    shiny
        7
    shiny  
       2017-11-01 22:07:52 +08:00
    小提示,PHP 文档里的代码会随 PHP 升级而发生变动。
    HYSS
        8
    HYSS  
       2017-11-01 22:13:46 +08:00
    又来黑 php
    49gd
        9
    49gd  
       2017-11-02 08:17:53 +08:00
    日常黑 php
    WytheHuang
        10
    WytheHuang  
       2017-11-02 09:12:22 +08:00
    麻烦看一下文档再来问好吗?
    http://php.net/manual/zh/migration70.php
    checgg
        11
    checgg  
       2017-11-02 09:55:11 +08:00
    日常黑 php..........
    mortence
        12
    mortence  
       2017-11-02 10:01:11 +08:00
    这。。。。。提示都有了,直接搜提示或者翻译一下应该就能猜到问题吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3362 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:24 · PVG 20:24 · LAX 05:24 · JFK 08:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.