V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
waibunleung
V2EX  ›  程序员

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

  •  
  •   waibunleung · Nov 1, 2017 · 4494 views
    This topic created in 3103 days ago, the information mentioned may be changed or developed.
    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 replies    2017-11-02 10:01:11 +08:00
    carlclone
        1
    carlclone  
       Nov 1, 2017 via Android
    你是来黑 PHP 的吧
    wdlth
        2
    wdlth  
       Nov 1, 2017
    Changelog ¶

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

    文档里面不是已经说了么……
    ruchee
        3
    ruchee  
       Nov 1, 2017
    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  
       Nov 1, 2017
    用了 7 独有的特性呗,多简单的事。。
    lepig
        5
    lepig  
       Nov 1, 2017
    楼主的例子不就是 Example #3 拷贝过来的么

    完全不看文档。
    oswuhan
        6
    oswuhan  
       Nov 1, 2017
    这种水分大的问题,直接去 https://segmentfault.com/上问,同道中人很多
    shiny
        7
    shiny  
    PRO
       Nov 1, 2017
    小提示,PHP 文档里的代码会随 PHP 升级而发生变动。
    HYSS
        8
    HYSS  
       Nov 1, 2017
    又来黑 php
    49gd
        9
    49gd  
       Nov 2, 2017
    日常黑 php
    WytheHuang
        10
    WytheHuang  
       Nov 2, 2017
    麻烦看一下文档再来问好吗?
    http://php.net/manual/zh/migration70.php
    checgg
        11
    checgg  
       Nov 2, 2017
    日常黑 php..........
    mortence
        12
    mortence  
       Nov 2, 2017
    这。。。。。提示都有了,直接搜提示或者翻译一下应该就能猜到问题吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2112 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 103ms · UTC 00:33 · PVG 08:33 · LAX 17:33 · JFK 20:33
    ♥ Do have faith in what you're doing.