PHP强制转换为我的课程 [英] PHP Cast to my class
本文介绍了PHP强制转换为我的课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这不可能:
$user = (User) $u[0];
但这是可能的
$bool = (boolean) $res['success'];
我使用PHP 7.0.
I use PHP 7.0.
推荐答案
据我所知,在PHP中,您只能转换为某些类型:
As I know, in PHP you can only cast to some types:
(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 来检查特定类型:
Instead you could use instanceof to check of specific type:
if($yourvar instanceof YourClass) {
//DO something
} else {
throw new Exception('Var is not of type YourClass');
}
编辑
正如SzabolcsPáll在回答中所提到的,也可以声明返回类型或参数类型,但在这种情况下,如果类型不匹配,则会引发异常( TypeError )
As mentioned by Szabolcs Páll in his answer, it is also possible to declare a return type or parameter type, but in that cases an exception (TypeError) will be throwen, if the type does not match.
function test(): string
{
return 'test';
}
function test(string $test){
return "test" . $test;
}
自PHP 7.2起,还可以通过添加?使类型为空.在他们面前:
Since PHP 7.2 it is also possible to make the types nullable by adding ? in front of them:
function test(): ?string
{
return null;
}
这篇关于PHP强制转换为我的课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文