Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP7.4 中属性类型约束导致 EasySwoole/SplBean 过滤掉了没有初值的属性 #262

Closed
endwiki opened this issue Dec 2, 2019 · 1 comment

Comments

@endwiki
Copy link

endwiki commented Dec 2, 2019

在 PHP7.4 中加入了属性类型约束的新特性,如下:

class UserBean extends SplBean
{
    protected string $username;
    protected int $status = 1;
}

属性的类型约束可以使得代码更加严谨,类型的错误更早的暴露。但是上面的代码在 EasySwoole 中会有如下问题:

(new UserBean(['username => 'admin', 'stauts' => 1]))->toArray();   // 输出的数组中没有 $username

经过排查,我发现在 EasySwoole 的 SplBean 类中,有如下的代码,导致了问题的发生:

    final public function allProperty(): array
    {
        $data = [];
        // 循环 $this 过滤掉了有类型约束但是没有赋予初值的成员属性
        foreach ($this as $key => $item) {
            array_push($data, $key);
        }
        // xxx: 省略
    }

在 PHP7.4 之前,因为没有类型提示,所以都会正常输出所有不是 Private保护的属性,在 PHP7.4 之后,因为加入了类型约束,导致了没有赋初值但是有类型提示的成员属性被过滤掉了(通过对$this的遍历)。

最后,提供最小的测试实例,希望我把这个问题描述清楚了:

class SplBean
{
    // 属性类型约束,PHP7.4 新特性
    protected int $sku_id = 0;
    protected int $spu_id;

    public function __construct()
    {
        foreach ($this as $key => $value) {
            // 如果属性有类型提示,只能循环出有默认值的属性,即 $sku_id;
            // 如果属性没有类型提示,则不管有没有默认值,都能循环出来, 即 $sku_id, $spu_id;
            var_dump($key);
        }
    }
}
@kiss291323003
Copy link
Contributor

已经兼容了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants