如果您嘗試從實體方法(僅限類別中)轉換特殊的 $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", 'Type', 'Succeed?', 'Converted');
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();
?>
Here is the result
類型 成功? 已轉換
bool 1 Foo 物件
(
)
注意:類別 Foo 的物件無法轉換為 int,位於 C:\php\examples\oop-settype-this.php 的第 9 行
int 1 Foo 物件
(
)
注意:類別 Foo 的物件無法轉換為 float,位於 C:\php\examples\oop-settype-this.php 的第 10 行
float 1 Foo 物件
(
)
array 1 Foo 物件
(
)
object 1 Foo 物件
(
)
警告:settype():類型無效,位於 C:\php\examples\oop-settype-this.php 的第 14 行
unknowntype Foo 物件
(
)
NULL 1 Foo 物件
(
)
可捕捉的致命錯誤:類別 Foo 的物件無法轉換為字串,位於 C:\php\examples\oop-settype-this.php 的第 15 行
如果類別 Foo 實作了 __toString()
<?php
class Foo {
function __toString() {
return 'Foo 物件很棒!';
}
}
?>
因此,第一個程式碼片段不會產生 E_RECOVERABLE_ERROR,而是會印出與其他類型相同的字串,並且不會查看 __toString() 方法返回的字串。
希望這個說明對您有所幫助! :)