search

php magic method

Nov 23, 2016 pm 01:58 PM
phpmagic method

__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state () and __clone() are called "Magic methods" in PHP. You cannot use these method names when naming your own class methods unless you want to use their magic functionality.

PHP reserves all class methods starting with __ (two underscores) as magic methods. Therefore, when defining class methods, except for the above magic methods, it is recommended not to prefix them with __.

__sleep() and __wakeup()

publicarray__sleep (void)

void__wakeup (void)

serialize() function will check whether there is a magic method __sleep() in the class. If present, this method will be called first, and then the serialization operation will be performed. This function can be used to clean an object and return an array containing the names of all variables in the object that should be serialized. If the method returns nothing, NULL is serialized and an E_NOTICE level error is generated.

Note:

__sleep() cannot return the name of the private member of the parent class. Doing so will generate an E_NOTICE level error. You can use the Serializable interface instead. The

__sleep() method is often used to submit uncommitted data, or similar cleaning operations. At the same time, this function is useful if you have some large objects but do not need to save them all.

In contrast, unserialize() checks whether there is a __wakeup() method. If it exists, the __wakeup method will be called first to prepare the resources needed by the object in advance.

__wakeup() is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.

Example #1 Sleep and wakeup

class Connection
{
    protected $link;
    private $server,$username,$password,$db;
    public function __construct($server,$username,$password,$db)
    {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this -> db = $db;
        $this -> connect();
    }
    private function connect(){
        $this -> link = mysql_connect($this->server,$this->username,$this->password);
        mysql_select_db($this->db,$this->link);
    }
    public function __sleep(){
        return array('server','username','password','db');
    }
    public function __wakeup(){
        $this->connect();
    }
}

__toString()

public string __toString ( void )

__toString() method is used for how a class should respond when it is treated as a string. For example, echo $obj; should display something. This method must return a string, otherwise a fatal error of level E_RECOVERABLE_ERROR will be issued.

You cannot throw exceptions in the __toString() method, doing so will result in a fatal error.

Example #2 Simple example

class TestClass
{
    public $foo;
    public function __construct($foo)
    {
        $this->foo = $foo;
    }
    public function __toString(){
        return $this->foo;
    }
}
$class = new TestClass('Hello');
echo $class;

Output result:

Hello

It should be pointed out that before PHP 5.2.0, the __toString() method can only take effect when used directly in echo or print. After PHP 5.2.0, it can be used in any string environment (such as through printf(), using the %s modifier), but cannot be used in non-string environments (such as using the %d modifier). As of PHP 5.2.0, converting an object that does not define the __toString() method to a string will generate an E_RECOVERABLE_ERROR level error.

__invoke()

mixed__invoke ([ $... ] )

When trying to call an object by calling a function, the __invoke() method will be automatically called.

Note:

This feature is only available in PHP 5.3.0 and above.

Example #3 Use __invoke()

class CallableClass
{
    function __invoke($x){
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));

Output result:

int(5)

bool(true)

__set_state()

static object __set_state ( array $properties )

Since PHP 5.1.0 This static method is called when var_export() is called to export a class.

The only parameter of this method is an array, which contains class properties arranged in the format of array('property' => value, ...) .

Example #4 Using __set_state()> (from PHP 5.1.0)

class A
{
    public $var1;
    public $var2;
    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj -> var1 = $an_array['var1'];
        $obj -> var2 = $an_array['var2'];
        return $obj;
    }
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b='.var_export($a,true).';');
var_dump($b);

Output result:

object(A)#2 (2) { ["var1"]=> int(5) [" var2"]=> string(3) "foo" }


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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools