如果您尝试从实例方法(仅在类中)中转换特殊的 $this 变量
* 如果类型是 'bool'、'array'、'object' 或 'NULL',PHP 将静默返回 TRUE 且 $this 保持不变
* 如果类型是 'int'、'float' 或 'double',PHP 将生成 E_NOTICE,并且 $this 不会被转换
* 当类型为 'string' 且类未定义 __toString() 方法时,PHP 将抛出可捕获的致命错误
除非作为第二个参数传递的新变量类型无效,否则 settype() 将返回 TRUE。在所有情况下,对象都将保持不变。
<?php
class Foo {
function test() {
printf("%-20s %-20s %s\n", '类型', '成功?', '转换后');
printf("%-20s %-20s %s\n", 'bool', settype($this, 'bool'), print_r($this, TRUE));
printf("%-20s %-20s %s\n", 'int', settype($this, 'int'), print_r($this, TRUE));
printf("%-20s %-20s %s\n", 'float', settype($this, 'float'), print_r($this));
printf("%-20s %-20s %s\n", 'array', settype($this, 'array'), print_r($this, TRUE));
printf("%-20s %-20s %s\n", 'object', settype($this, 'object'), print_r($this, TRUE));
printf("%-20s %-20s %s\n", 'unknowntype', settype($this, 'unknowntype'), print_r($this, TRUE));
printf("%-20s %-20s %s\n", 'NULL', settype($this, 'NULL'), print_r($this, TRUE));
printf("%-20s %-20s %s\n", 'string', settype($this, 'string'), print_r($this, TRUE));
}
}
$a = new Foo();
$a->test();
?>
以下是结果
类型 成功? 转换后
bool 1 Foo Object
(
)
Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9
int 1 Foo Object
(
)
Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10
float 1 Foo Object
(
)
array 1 Foo Object
(
)
object 1 Foo Object
(
)
Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14
unknowntype Foo Object
(
)
NULL 1 Foo Object
(
)
Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15
如果类 Foo 实现 __toString()
<?php
class Foo {
function __toString() {
return 'Foo object is awesome!';
}
}
?>
所以第一个代码片段不会生成 E_RECOVERABLE_ERROR,而是打印与其他类型相同的字符串,而不是查看 __toString() 方法返回的字符串。
希望这有帮助!:)