如何做招聘网站对比分析,狠狠做网站 百度一下,国际局势最新消息,qq官网登录入口电脑版_toString方法是在打印对象时自动调用的魔术方法,如果不声明会报以下错 Catchable fatal error: Object of class String could not be converted to 示例: PHP里有很多的字符串函数,假如要先过滤字符首尾的空格,再求出字符串的长度,一般会这么写:strlen(trim($str));如果要实…_toString方法是在打印对象时自动调用的魔术方法,如果不声明会报以下错 Catchable fatal error: Object of class String could not be converted to 示例: PHP里有很多的字符串函数,假如要先过滤字符首尾的空格,再求出字符串的长度,一般会这么写: strlen(trim($str)); 如果要实现JS里的链式操作,比如像下面这样,应该怎么实现? $str-trim()-strlen() 很简单,先实现一个String类,对这个类的对象调用方法进行处理时,触发__call魔术方法,接着执行call_user_func或者call_user_func_array即可. 以下是简单的实现 ?php
class String
{public $value;//字符串的值public function __construct($str){$this-value $str;}public function __call($method, $args){array_push($args,$this-value);$this-value call_user_func_array($method,$args);return $this;}//打印对象时返回对象的value值public function __toString(){return strval($this-value);}
}
$str new String(20150816);
echo $str-trim()-strtotime()-date(Y年m月d日);运行结果如下 2015年08月16日PHP的__toString魔术方法的设计原型来源于Java,Java中也有这么一个方法,而且在Java中,这个方法被大量使用,对于调试程序比较方便. 实际上,__toString方法也是一种序列化, PHP自带的serialize/unserialize也是进行序列化的, 但是这组函数序列化时会产生一些无用信息,如属性字符串长度,造成存储空间无谓浪费.因此,可以实现自己的序列化和反序列化方法,或者json_encode/json_decode也是一个不错的选择 转载于:https://www.cnblogs.com/chenqionghe/p/4735720.html