search

PHP magic methods:

__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), Methods such as __toString(), __invoke(), __set_state(), __clone() and __debugInfo() 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.

__construct(),类的构造函数
__destruct(),类的析构函数
__call(),在对象中调用一个不可访问方法(私有或者不存在)时调用
__callStatic(),用静态方式中调用一个不可访问方法时调用
__get(),获得一个类的成员变量时调用
__set(),设置一个类的成员变量时调用
__isset(),当对不可访问属性调用isset()或empty()时调用
__unset(),当对不可访问属性调用unset()时被调用。
__sleep(),执行serialize()时,先会调用这个函数
__wakeup(),执行unserialize()时,先会调用这个函数
__toString(),类被当成字符串时的回应方法
__invoke(),调用函数的方式调用一个对象时的回应方法
__set_state(),调用var_export()导出类时,此静态方法会被调用。
__clone(),当对象复制完成时调用

__construct() and __destruct()
The constructor __construct() is called when the object is created, and the destructor __destruct() is called when the object dies

<?php &#160;
class ConDes
{
&#160;&#160;&#160; protected $a = &#39;&#39;;

&#160;&#160;&#160; function __construct(){
&#160;&#160;&#160;&#160;&#160;&#160;&#160; echo &#39;在构造函数中<br>';
    }

    function __destruct(){

        echo '在析构函数中<br>';
    }
}

$val = new ConDes();
unset($val);

?><pre name="code" class="php">
 output:

In the constructor and in the destructor

__call() and __callStatic() are called when an inaccessible method is called in the object. The latter is a static method.

<?php &#160;
class MethodTest &#160;
{
&#160;&#160;&#160; public function __call ($name, $arguments) {
&#160;&#160; &#160;var_dump($arguments);
&#160;&#160;&#160;&#160;&#160;&#160;&#160; echo "object method $name and ".implode(&#39;,&#39;,$arguments)."<br>";
    }

    public static function __callStatic ($name, $arguments) {
        echo "static method $name and ".implode(',',$arguments)."<br>";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context','another arg');
MethodTest::runTest('in static context');  
?>
output:

array (size=2)
0 => string 'in object context' (length=17)
1 => string 'another arg' (length=11)
object method runTest and in object context,another arg
static method runTest and in static context

__get(), __set(), __isset() and __unset()
These two functions are called when getting an inaccessible class member variable or setting an inaccessible class member variable .

<?php class MethodTest  
{
    private $data = array();
    private $a = &#39;&#39;;
    public $bbb = &#39;&#39;;

    public function __set($name, $value){
        $this->data[$name] = $value;
		echo '__set';
		var_dump($this->data);
    }

    public function __get($name){
		echo '__get';
		var_dump($this->data);
        if(array_key_exists($name, $this->data))
            return $this->data[$name];
        return NULL;
    }

    public function __isset($name){
		echo '__isset';
        return isset($this->data[$name]);
    }

    public function __unset($name){
		echo '__unset';
        unset($this->data[$name]);
    }
}

$in = new MethodTest();
$in->a = 'aaaa';
$aaa = $in->a;
$res = isset($in->c)? 'set':'not set';
echo '<br>'.$res.'<br>';
unset($in->a);
?>
output:

__set
array (size=1)
'a' => string 'aaaa' (length=4)
__get
array (size=1)
'a' => string 'aaaa' (length=4)
__isset
not set
__unset

__sleep() and __wakeup()
When we execute serialize() and unserialize(), these two functions will be called first. For example, when we serialize an object, the object has a database link. If we want to restore the link state during deserialization, we can restore the link by reconstructing these two functions.

<span></span>

<?php class Connection {
&#160;&#160;&#160; public $link;
&#160;&#160;&#160; private $server, $username, $password, $db;
&#160;&#160; &#160;
&#160;&#160;&#160; public function __construct($server, $username, $password, $db)
&#160;&#160;&#160; {
&#160;&#160;&#160;&#160;&#160;&#160;&#160; $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()
    {
    echo 'sleep<br>';
        return array('server', 'username', 'password', 'db');
    }
    
    public function __wakeup()
    {
    echo 'wakeup<br>';
        $this->connect();
    }
}


$a = new Connection('localhost','mosi','moshi','test');
$sql = 'select id,username from user limit 1';
$res = mysql_query($sql,$a->link);
$res = mysql_fetch_array($res);
var_dump($res);

$sres = serialize($a);
mysql_close($a->link);
//unset($a);

$unsres = unserialize($sres);
var_dump($unsres);
$sql = 'select id,username from user limit 1';
$ress = mysql_query($sql,$unsres->link);
$ress = mysql_fetch_array($ress);
var_dump($ress);


?>
output:

<span>array (size=4)<br> 0 => string '1' (length=1)<br> 'id' => string '1' (length=1)<br> 1 => string 'm0sh1' (length =5)<br> 'username' => string 'm0sh1' (length=5)<br>sleep<br>wakeup<br>object(Connection)[2]<br> public 'link' => resource(6, mysql link)<br> private 'server ' => string 'localhost' (length=9)<br> private 'username' => string 'moshi' (length=4)<br> private 'password' => string 'moshi' (length=5)<br> private ' db' => string 'test' (length=4)<br>array (size=4)<br> 0 => string '1' (length=1)<br> 'id' => string '1' (length=1 )<br> 1 => string 'm0sh1' (length=5)<br> 'username' => string 'm0sh1' (length=5)</span>

<span>__toString()<br> when the object is treated as a string response method. For example, using echo $obj;</span>

<span></span>

<?php class TestClass  
{
    public function __toString() {
        return &#39;this is a object&#39;;
    }
}

$class = new TestClass();
echo $class;  
?>
output:

<span></span><span></span>this is a object

This method can only return a string, and exceptions cannot be thrown in this method, otherwise a fatal error will occur.

__invoke()
The response method when calling an object by calling a function.

<?php class Invoke{
	public function __invoke(){
		echo &#39;in invoke<br>';
	}
}

class noInvoke{

}

$obj = new Invoke();
$obj();

var_dump(is_callable($obj));

$obj2 = new noInvoke();
//$obj2();
var_dump(is_callable($obj2));

Output:

in invoke
boolean true
boolean false

__set_state()
This static method will be called when var_export() is called to export a class.

<?php class A  
{
    public $var1;
    public $var2;
	public static function __set_state ($arr) {
        $obj = new A;
        $obj->var1 = 'var11';
        $obj->var2 = $arr['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
var_dump($a);  
var_export($a);  

eval('$ress = '.var_export($a,true).';');
var_dump($ress);

?>

Output:

object(A)[1]
public 'var1' => int 5
public 'var2' => string 'foo' (length=3)
A::__set_state(array( 'var1' => 5, 'var2' => 'foo', ))
object(A)[2]
public 'var1' => string 'var11' (length=5)
public 'var2' => string 'foo' (length=3)

__clone()
Called when the object copy is completed.

<?php class Singleton {  
    private static $_instance = NULL;

    // 私有构造方法 
    private function __construct() {}

    public static function getInstance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new Singleton();
        }
        return self::$_instance;
    }

    // 防止克隆实例
    public function __clone(){
        die(&#39;Clone is not allowed error: &#39; . E_USER_ERROR);
    }
}


$a = Singleton::getInstance();
$b = Singleton::getInstance();

if( $a === $b ){
	echo &#39;equal<br>';
}

$c = clone $b;
?>

Output:

equal
Clone is not allowed error: 256


PHP Magic Constants: Introduction here

The above has introduced the magic methods in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!