search
HomeBackend DevelopmentPHP TutorialSerialization of objects in php, php object serialization_PHP tutorial

Serialization of objects in php, php object serialization

We all know that PHP serialization can convert variables, including objects, into continuous bytes data. You can Store the serialized variables in a file or transmit them over the network, and then deserialize them back to the original data. This article gives you a detailed introduction to PHP serialization. PHP can successfully store the properties and methods of a class that you define before deserializing its object. Sometimes you may need an object to be executed immediately after deserializing it. For such purposes, PHP automatically looks for the __sleep and __wakeup methods.

When an object is serialized by PHP, PHP will call the __sleep method (if it exists). After deserializing an object, PHP will call the __wakeup method. Neither method accepts parameters. __sleep method Must return an array containing the attributes that need to be serialized. PHP will discard the values ​​​​of other attributes. Without the __sleep method, PHP will save all attributes. ​
<?<span>php
</span><span>/*</span><span>
 * 
 * @Authors peng--jun 
 * @Email   1098325951@qq.com
 * @Date    2016-01-23 14:40:38
 * @Link    </span><span>http://www.cnblogs.com/xs-yqz/</span><span>
 * @version $Id$
 ==========================================
 </span><span>*/</span><span>
 header(</span><span>"</span><span>Content-type: text/html; charset=UTF-8</span><span>"</span><span>); 
 </span><span>class</span><span> Person{
     </span><span>private</span><span> $name;
     </span><span>private</span><span> $sex;
     </span><span>private</span><span> $age;

     function __construct($name,$age,$sex){
         $</span><span>this</span>->name =<span> $name;
         $</span><span>this</span>->age =<span> $age;
         $</span><span>this</span>->sex =<span> $sex;
     }
     function say(){
         echo </span><span>"</span><span>我的名字:</span><span>"</span>.$<span>this</span>->name.<span>"</span><span>性别为: </span><span>"</span>.$<span>this</span>->sex.<span>"</span><span>年龄为:</span><span>"</span>.$<span>this</span>-><span>age;
     }

   <span>//在类中添加此方法,在串行化的时候自动调用并返回数组</span>
     function __sleep(){
     $arr </span>= array(<span>"</span><span>name</span><span>"</span>,<span>"</span><span>age</span><span>"</span>);<span>//</span><span>数组中的成员$name和$age将被串行化,成员$sex则将被忽略。</span>
     <span>return</span><span>($arr);<span>//使用__sleep()方法的时候必须返回一个数组。</span>
    }
<span>    //在反串行化对象时自动调用该方法,没有参数也没有返回值</span>
    function __wakeup(){
        $</span><span>this</span>->age = <span>40</span><span>;<span>//在重新组织对象的时候,为新对象中的$age属性重新赋值</span>
    }
}

 $person1 </span>= <span>new</span> Person(<span>"</span><span>张三</span><span>"</span>,<span>20</span>,<span>"</span><span>男</span><span>"</span><span>);
 $person1_string </span>=<span> serialize($person1);
 echo $person1_string.</span><span>"</span><span><br /></span><span>"</span><span>;

</span><span>//</span><span>反串行化对象,并自动调用了__wakeup()方法重新为独享中的age赋值。</span>
$person2 =<span> unserialize($person1_string);
$person2</span>-><span>say();

 </span>?>

The output result is:

O:<span>6</span>:<span>"</span><span>Person</span><span>"</span>:<span>2</span>:{s:<span>12</span>:<span>"</span><span>Personname</span><span>"</span>;s:<span>6</span>:<span>"</span><span>张三</span><span>"</span>;s:<span>11</span>:<span>"</span><span>Personage</span><span>"</span>;i:<span>20</span><span>;}
我的名字:张三性别为: 年龄为:</span><span>40</span>

2. Save the serialized string to the file, read the string from the file, and deserialize the instance.

 header(<span>"</span><span>Content-type: text/html; charset=UTF-8</span><span>"</span><span>); 
 </span><span>class</span><span> Person{
     </span><span>private</span><span> $name;
     </span><span>private</span><span> $sex;
     </span><span>private</span><span> $age;

     function __construct($name,$age,$sex){
         $</span><span>this</span>->name =<span> $name;
         $</span><span>this</span>->age =<span> $age;
         $</span><span>this</span>->sex =<span> $sex;
     }
     function say(){
         echo </span><span>"</span><span>我的名字:</span><span>"</span>.$<span>this</span>->name.<span>"</span><span>性别为: </span><span>"</span>.$<span>this</span>->sex.<span>"</span><span>年龄为:</span><span>"</span>.$<span>this</span>-><span>age;
     }
 }

 $person1 </span>= <span>new</span> Person(<span>"</span><span>张三</span><span>"</span>,<span>21</span>,<span>"</span><span>男</span><span>"</span><span>);
 $person1_string </span>=<span> serialize($person1);
 file_put_contents(</span><span>"</span><span>file.txt</span><span>"</span>, $person1_string);<br /><br />
 header(<span>"</span><span>Content-type: text/html; charset=UTF-8</span><span>"</span><span>); 
  </span><span>class</span><span> Person{
     </span><span>private</span><span> $name;
     </span><span>private</span><span> $sex;
     </span><span>private</span><span> $age;

     function __construct($name,$age,$sex){
         $</span><span>this</span>->name =<span> $name;
         $</span><span>this</span>->age =<span> $age;
         $</span><span>this</span>->sex =<span> $sex;
     }
     function say(){
         echo </span><span>"</span><span>我的名字:</span><span>"</span>.$<span>this</span>->name.<span>"</span><span> 性别为:</span><span>"</span>.$<span>this</span>->sex.<span>"</span><span> 年龄为:</span><span>"</span>.$<span>this</span>-><span>age;
     }
 }

 $person2_string </span>= file_get_contents(<span>"</span><span>file.txt</span><span>"</span><span>);
 $person2 </span>=<span> unserialize($person2_string);<span>//反串性化重新形成对象$person2.</span>
 $person2</span>-><span>say();
</span>?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1094586.htmlTechArticleSerialization of objects in php, php object serialization We all know that PHP serialization can convert variables Including objects, converted into continuous bytes data, you can store the serialized variables in a...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor