PHP7.4+ 严格模式全部类型以及使用方法,可迭代(iterable) 接口的使用方法

PHP7.4+ 严格模式全部类型以及使用方法,可迭代(iterable) 接口的使用方法

远航
2022-05-27 / 0 评论 / 139 阅读 / 正在检测是否收录...

PHP7.4+ 严格模式全部类型属性定义
// 定义静态类型属性
//布尔型(bool)
private bool $flag = true;
//整型(int)
public int $age = 18;
//浮点型(float)
private float $money = 0.03;
//字符串(string)
public string $name = '';
//数组(array)
private array $news = [];
//可迭代,遍历(iterable) 接口
private UserArrStruct $arrObj;
//对象 其他类的对象
private User $userInfo;
//?(nullable) 可为空
private ?User $userInfoNull;
//self 自己
private self $myObj;
//parent 父类
private parent $myUser;
//类和接口
private ArrayAccess $arrayAccess;
带静态返回类型以及带类型参数的方法举例
// 定义带返回类型方法 和带静态类型参数
//布尔型(bool)
public function getBool(bool $flag): bool
{
    return $flag;
}

//整型(int)
public function getInt(int $age): int
{
    return $age;
}

//浮点型(float)
public function getFloat(float $money): float
{
    return $money;
}

//字符串(string)
public function getString(string $name): string
{
    return $name;
}

//数组(array)
public function getArray(array $array): array
{
    return $array;
}

//可迭代,遍历(iterable) 接口
public function getUserList(UserArrStruct $userList): UserArrStruct
{
    return $userList;
}

//对象 其他类的对象
public function getUserInfo(User $userInfo): User
{
    return $userInfo;
}

//?(nullable) 可为空
public function getUserInfoNull(?User $userInfo): ?User
{
    return $userInfo;
}

//self 自己
public function getSelf(self $type): self
{
    return $type;
}

//parent 父类
public function getParent(User $userInfo): parent
{
    return $userInfo;
}
//类和接口 参考 getUserList()
可迭代,遍历(iterable) 接口的使用方法

require 'User.php';

class UserArrStruct implements \Iterator
{
    private int $position = 0;
    private array $array = [];

    public function __construct($array = [])
    {
        $this->position = 0;
        $this->array = $array;
    }

    /** 这个方法返回遍历的每个val
     * @return mixed
     */
    public function current(): User
    {
        return $this->array[$this->position];
    }

    /** 这个方法控制下一次返回的KEY
     * @return mixed
     */
    public function next()
    {
        ++$this->position;
    }

    public function key()
    {
        return $this->position;
    }

    public function valid(): bool
    {
        return isset($this->array[$this->position]);
    }

    public function rewind()
    {
        $this->position = 0;
    }
}
使用方法
// 引入类文件
require_once 'UserArrStruct.php';
// 定义严格数组储存User对象
$liBai = new User('李白', '108', '男');
$xiaoQ = new User('小乔', '120', '女');
$userArr = [$liBai, $xiaoQ];
// 实例化严格可迭代对象并赋值
$userList = new UserArrStruct($userArr);
// 迭代对象
foreach ($userList as $k => $userInfo) {
    echo '姓名:' . $userInfo->name . PHP_EOL;
    echo '年龄:' . $userInfo->age . PHP_EOL;
    echo PHP_EOL;
}
打印结果

使用效果:和平常的数组比起来ide提示非常友好

iShot_2022-05-27_23.57.33.png

0

评论

博主关闭了当前页面的评论