php中怎么定义类_PHP: 预定义类 - Manual

If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

* An implementation of var_export() that is compatible with instances

* of stdClass.

* @param mixed $variable The variable you want to export

* @param bool $return If used and set to true, improved_var_export()

*     will return the variable representation instead of outputting it.

* @return mixed|null Returns the variable representation when the

*     return parameter is used and evaluates to TRUE. Otherwise, this

*     function will return NULL.

*/functionimproved_var_export($variable,$return=false) {

if ($variableinstanceofstdClass) {$result='(object) '.improved_var_export(get_object_vars($variable),true);

} else if (is_array($variable)) {$array= array ();

foreach ($variableas$key=>$value) {$array[] =var_export($key,true).' => '.improved_var_export($value,true);

}$result='array ('.implode(', ',$array).')';

} else {$result=var_export($variable,true);

}

if (!$return) {

print$result;

returnnull;

} else {

return$result;

}

}// Example usage:$obj= newstdClass;$obj->test='abc';$obj->other=6.2;$obj->arr= array (1,2,3);improved_var_export((object) array ('prop1'=>true,'prop2'=>$obj,'assocArray'=> array ('apple'=>'good','orange'=>'great')

));/* Output:

(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))

*/?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值