settype php,PHP: settype - Manual

If you attempt to convert the special $this variable from an instance method (only in classes) :

* PHP will silently return TRUE and leave $this unchanged if the type was 'bool', 'array', 'object' or 'NULL'

* PHP will generate an E_NOTICE if the type was 'int', 'float' or 'double', and $this will not be casted

* PHP will throw a catchable fatal error when the type is 'string' and the class does not define the __toString() method

Unless the new variable type passed as the second argument is invalid, settype() will return TRUE. In all cases the object will remain unchanged.

functiontest() {printf("%-20s %-20s %s\n",'Type','Succeed?','Converted');// settype() should throw a fatal error, as $this cannot be re-assignedprintf("%-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= newFoo();$a->test();?>Here is the result :

Type                 Succeed?             Converted

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

If the class Foo implements __toString() :

return'Foo object is awesome!';

}// ...}?>So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString() method.

Hope this helps !  :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值