Home > php教程 > php手册 > body text

PHP中stdClass的意义

PHPz
Release: 2018-09-30 15:49:20
forward
829 people have browsed it

在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 )
Copy after login

get_object_vars的作用是返回由对象属性组成的关联数组。它的效果跟这样定义数组其实是一样的:

$tanteng = array();$tanteng['name'] = 'tanteng';$tanteng['email'] = 'xxx@qq.com';
Copy after login

可以这样理解: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);
Copy after login

这里

user,但其实并没有新开辟一块内存存储变量,

myUser改变属性页就改变了$user的属性,并不是新建一个副本,如果程序中有许多这样的操作,使用stdClass的方式可以节省内存开销。

运行结果:

stdClass Object
(
    [name] => flypig
    [hehe] => hehe
)
stdClass Object
(
    [name] => flypig
    [hehe] => hehe
)
stdClass Object
(
    [name] => flypig
    [hehe] => hehe
)
Copy after login

从结果可以看出,改变

user声明的stdClass属性。而如果

myUser,那就拷贝了一个副本给$myUser,这样增大系统开销。

当然,你也可以反过来,把一个数组转换为对象:

$hehe['he1'] = 'he1';$hehe['he2'] = 'he2';$hh = (object) $hehe;
print_r($hh);
Copy after login

打印结果:

stdClass Object ( [he1] => he1 [he2] => he2 )

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!