355 of 410 menu

The __sleep Method

The __sleep method is automatically called when serializing an object using the serialize function. This method should return an array of property names that should be included in the serialized representation of the object.

Syntax

public function __sleep(): array;

Example

Let's create a class and implement the __sleep method to serialize only specific properties:

<?php class User { public $name = 'John'; public $age = 30; private $password = '12345'; public function __sleep() { return ['name', 'age']; } } $user = new User(); echo serialize($user); ?>

Code execution result:

'O:4:"User":2:{s:4:"name";s:4:"John";s:3:"age";i:30;}'

Example

Using __sleep to exclude confidential data from serialization:

<?php class Account { public $login = 'admin'; private $password = 'secret'; public $email = 'admin@example.com'; public function __sleep() { return ['login', 'email']; } } $account = new Account(); echo serialize($account); ?>

Code execution result:

'O:7:"Account":2:{s:5:"login";s:5:"admin";s:5:"email";s:17:"admin@example.com";}'

See Also

  • the __wakeup method,
    which is called during object deserialization
  • the serialize function,
    which serializes data
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline