new stdClass()

王朝百科·作者佚名  2012-04-07  
宽屏版  字体: |||超大  

new stdClass()定义stdClass在PHP5才开始被流行。而stdClass也是zend的一个保留类。stdClass是PHP的一个基类,所有的类几乎都继承这个类,所以任何时候都可以被new,可以让这个变量成为一个object。同时,这个基类又有一个特殊的地方,就是没有方法。凡是用new stdClass()的变量,都不可能会出现$a->test()这种方式的使用。PHP5的对象的独特性,对象在任何地方被调用,都是引用地址型的,所以相对消耗的资源会少一点。在其它页面为它赋值时是直接修改,而不是引用一个拷贝。

英文解释The PHP stdClass() is something that isn’t well documented but i will try to shed some light into the matter. stdClass is a default PHP object which has no predefined members. The name stdClass is used internally by Zend and is reserved. So that means that you cannot define a class named stdClass in your PHP code.

It can be used to manually instantiate generic objects which you can then set member variables for, this is useful for passing objects to other functions or methods which expect to take an object as an argument. An even more likely usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key in the array.

例子<?php

function arrayToObject($array) {

if(!is_array($array)) {

return $array; }

$object = new stdClass();

if (is_array($array) && count($array) > 0) {

foreach ($array as $name=>$value) {

$name = strtolower(trim($name));

if (!empty($name)) {

$object->$name = arrayToObject($value);

}

}

return $object;

}

else { return FALSE; }

}

?>

 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝百科 版权所有