PHP 投射到我的班级

2022-08-30 12:24:02

为什么这是不可能的:

$user = (User) $u[0];

但这是可能的

$bool = (boolean) $res['success'];

我使用 PHP 7.0。


答案 1

据我所知,在PHP中,您只能转换为某些类型:

(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(binary) - cast to binary string (PHP 6)
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5) (depracted in PHP 7.2) (removed in 8.0)

(请参见类型转换)

相反,您可以使用 instanceof 来检查特定类型:

if($yourvar instanceof YourClass) {
    //DO something
} else {
    throw new Exception('Var is not of type YourClass');
}

编辑

正如 Szabolcs Páll 在他的回答中提到的,也可以声明返回类型参数类型,但在这种情况下,如果类型不匹配,将引发异常(TypeError)。

function test(): string
{
    return 'test';
}

function test(string $test){
    return "test" . $test;
}

从 PHP 7.2 开始,也可以通过添加 ?在他们面前:

function test(): ?string
{
    return null;
}

答案 2

您可以使用 PHPDoc

/** @var User $user */
$user = $u[0];

推荐