V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
waibunleung
V2EX  ›  问与答

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

  •  1
     
  •   waibunleung · Nov 1, 2017 · 2689 views
    This topic created in 3111 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
    1 replies    2017-11-01 21:45:59 +08:00
    3IOhG7M0knRu5UlC
        1
    3IOhG7M0knRu5UlC  
       Nov 1, 2017 via Android
    类型约束
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   918 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 20:22 · PVG 04:22 · LAX 13:22 · JFK 16:22
    ♥ Do have faith in what you're doing.