源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

PHP中STDCLASS用法实例分析

  • 时间:2020-08-20 20:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP中STDCLASS用法实例分析
本文实例讲述了PHP中STDCLASS用法。分享给大家供大家参考,具体如下: PHP中STDCLASS在我们开发应用中使用到的不多,但是PHP中STDCLASS作用是非常的大的,下面我们一起来看PHP中STDCLASS的用法. 在WordPress中很多地方使用stdClass来定义一个对象(而通常是用数组的方式),然后使用get_object_vars来把定义的对象『转换』成数组. 如下代码所示:
$tanteng = new stdClass();
$tanteng->name = 'tanteng';
$tanteng->email = 'xxx@qq.com';
$info = get_object_vars($tanteng);
print_r($info);
exit;

输出:
Array ( [name] => tanteng [email] => xxx@qq.com )

get_object_vars的作用是返回由对象属性组成的关联数组。它的效果跟这样定义数组其实是一样的:
$tanteng = array();
$tanteng['name'] = 'tanteng';
$tanteng['email'] = 'xxx@qq.com';

可以这样理解:stdClass是一个内置类,它没有成员变量,也没有成员方法的一个类,new一个stdClass就是实例化了一个『空』对象,它本身没什么意义,但是用stdClass定义有什么好处呢? 如下代码:
$user = new stdClass();
$user->name = 'gouki';
$user->hehe = 'hehe';
$myUser = $user;
$myUser->name = 'flypig';
print_r($user);
print_r($myUser);
print_r($user);
这里$myUser被赋值$user,但其实并没有新开辟一块内存存储变量,$myUser还是指的stdClass这个对象,通过$myUser改变属性页就改变了$user的属性,并不是新建一个副本,如果程序中有许多这样的操作,使用stdClass的方式可以节省内存开销. 运行结果:
stdClass Object
(
  [name] => flypig
  [hehe] => hehe
)
stdClass Object
(
  [name] => flypig
  [hehe] => hehe
)
stdClass Object
(
  [name] => flypig
  [hehe] => hehe
)

从结果可以看出,改变$myUser的属性确实改变了$user声明的stdClass属性,而如果$user是一个数组,赋值给$myUser,那就拷贝了一个副本给$myUser,这样增大系统开销. 当然,你也可以反过来,把一个数组转换为对象:
$hehe['he1'] = 'he1';
$hehe['he2'] = 'he2';
$hh = (object) $hehe;
print_r($hh);

打印结果:
stdClass Object ( [he1] => he1 [he2] => he2 )

更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/357.htm]PHP运算与运算符用法总结[/url]》、《[url=http://www.1sucai.cn/Special/495.htm]PHP网络编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部