• 请不要在回答技术问题时复制粘贴 AI 生成的内容
waibunleung
V2EX  ›  程序员

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

  •  
  •   waibunleung · Nov 1, 2017 · 4904 views
    This topic created in 3291 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
    carlclone
    Nov 1, 2017 via Android
    1
    你是来黑 PHP 的吧
    wdlth
    wdlth
    Nov 1, 2017
    2
    Changelog ¶

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

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

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