Home Backend Development PHP Tutorial magic method in php

magic method in php

Aug 08, 2016 am 09:30 AM
function gt public

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(),当对象复制完成时调用
Copy after login

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

<?php  
class ConDes
{
    protected $a = '';

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

    function __destruct(){

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

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

?><pre name="code" class="php">
Copy after login
Copy after login
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  
class MethodTest  
{
    public function __call ($name, $arguments) {
    var_dump($arguments);
        echo "object method $name and ".implode(',',$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');  
?>
Copy after login
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 = '';
    public $bbb = '';

    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);
?>
Copy after login
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>

&lt;?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-&gt;server = $server;
        $this-&gt;username = $username;
        $this-&gt;password = $password;
        $this-&gt;db = $db;
        $this-&gt;connect();
    }
    
    private function connect()
    {
        $this-&gt;link = mysql_connect($this-&gt;server, $this-&gt;username, $this-&gt;password);
        mysql_select_db($this-&gt;db, $this-&gt;link);
    }
    
    public function __sleep()
    {
    echo 'sleep&lt;br&gt;';
        return array('server', 'username', 'password', 'db');
    }
    
    public function __wakeup()
    {
    echo 'wakeup&lt;br&gt;';
        $this-&gt;connect();
    }
}


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

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

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


?&gt;
Copy after login
output:

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

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

$class = new TestClass();
echo $class;  
?&gt;
Copy after login
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.

&lt;?php
class Invoke{
	public function __invoke(){
		echo 'in invoke&lt;br&gt;';
	}
}

class noInvoke{

}

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

var_dump(is_callable($obj));

$obj2 = new noInvoke();
//$obj2();
var_dump(is_callable($obj2));
Copy after login

Output:

in invoke
boolean true
boolean false

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

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

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

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

?&gt;
Copy after login

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.

&lt;?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('Clone is not allowed error: ' . E_USER_ERROR);
    }
}


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

if( $a === $b ){
	echo 'equal&lt;br&gt;';
}

$c = clone $b;
?&gt;
Copy after login

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 of this Website
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

What are the differences between Huawei GT3 Pro and GT4?

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

What does function mean?

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Fix: Snipping tool not working in Windows 11

What is the difference between the developer version and the public version of iOS? What is the difference between the developer version and the public version of iOS? Mar 01, 2024 pm 12:55 PM

What is the difference between the developer version and the public version of iOS?

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

How to Fix Can't Connect to App Store Error on iPhone

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

What is the purpose of the 'enumerate()' function in Python?

See all articles