为什么这是不可能的:
$user = (User) $u[0];
Run Code Online (Sandbox Code Playgroud)
但这是可能的
$bool = (boolean) $res['success'];
Run Code Online (Sandbox Code Playgroud)
我使用PHP 7.0.
Sza*_*áll 12
如果您只想确保变量是 YourClass 的实例并让异常处理到类型系统,您可以使用以下函数:
function implicitFakeCast($myClass): YourClass
{
return $myClass;
}
Run Code Online (Sandbox Code Playgroud)
注意:这实际上不会进行任何转换,而是在类不匹配的情况下抛出异常,并让智能感知将其视为目标类的实例。
据我所知,在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)
Run Code Online (Sandbox Code Playgroud)
(参见类型转换)
相反,您可以使用instanceof来检查特定类型:
if($yourvar instanceof YourClass) {
//DO something
} else {
throw new Exception('Var is not of type YourClass');
}
Run Code Online (Sandbox Code Playgroud)
小智 9
您可以使用 PHPDoc
/** @var User $user */
$user = $u[0];
Run Code Online (Sandbox Code Playgroud)
在 php8 中这非常简单:
$item = (fn($item):YourClass=>$item)($item);
Run Code Online (Sandbox Code Playgroud)
对于确实希望能够转换为类类型的人。我找到了@borzilleri 的一个要点,它使用序列化和反序列化来实现这一点:https ://gist.github.com/borzilleri/960035 。
特尔;博士:
// make sure to include the namespace when casting
$className = "Some\\NameSpace\\SomeClassName";
$classNameLength = strlen( $className );
$castedItem = unserialize(
preg_replace(
'/^O:\d+:"[^"]++"/',
"O:$classNameLength:\"$className\"",
serialize( $item )
)
)
Run Code Online (Sandbox Code Playgroud)