PHP中STDCLASS在我们开发应用中使用到的不多,但是PHP中STDCLASS作用是非常的大的,下面我们一起来看PHP中STDCLASS的用法。
在WordPress中很多地方使用stdClass来定义一个对象(而通常是用数组的方式),然后使用get_object_vars来把定义的对象『转换』成数组。
如下代码所示:
PHP
$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的作用是返回由对象属性组成的关联数组。它的效果跟这样定义数组其实是一样的:
PHP
$tanteng = array();
$tanteng['name'] = 'tanteng';
$tanteng['email'] = 'xxx@qq.com';
可以这样理解:stdClass是一个内置类,它没有成员变量,也没有成员方法的一个类。new一个stdClass就是实例化了一个『空』对象,它本身没什么意义,但是用stdClass定义有什么好处呢?
如下代码:
PHP
$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的方式可以节省内存开销。
运行结果:
PHP
stdClass Object
(
[name] => flypig
[hehe] => hehe
)
stdClass Object
(
[name] => flypig
[hehe] => hehe
)
stdClass Object
(
[name] => flypig
[hehe] => hehe
)
从结果可以看出,改变$myUser的属性确实改变了$user声明的stdClass属性。而如果$user是一个数组,赋值给$myUser,那就拷贝了一个副本给$myUser,这样增大系统开销。
当然,你也可以反过来,把一个数组转换为对象:
PHP
$hehe['he1'] = 'he1';
$hehe['he2'] = 'he2';
$hh = (object) $hehe;
print_r($hh);
打印结果:
stdClass Object ( [he1] => he1 [he2] => he2 )

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use