PHP magic method: __construct __destruct

WBOY
Release: 2016-08-08 09:33:07
Original
2170 people have browsed it

From php5 and later versions, classes can use magic methods. PHP stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that function names do not start with __ unless it is to overload existing magic methods.

The existing magic methods in PHP include __construct, __destruct, __call, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __set_state and __clone.

This section will talk about __construct, __destruct:

__construct() - This method is called every time a new object is created

__destruct() - Executed when all references to the object are deleted or when the object is explicitly destroyed

<?php

/**
 * 清晰的认识__construct() __destruct
 */
class Example {

    public static $link;
    //在类实例化的时候自动加载__construct这个方法
    public function __construct($localhost, $username, $password, $db) {
        self::$link = mysql_connect($localhost, $username, $password);
        if (mysql_errno()) {
            die('错误:' . mysql_error());
        }
        mysql_set_charset('utf8');
        mysql_select_db($db);
    }

    /**
     * 通过__construct链接好数据库然后执行sql语句......
     */
    
    //当类需要被删除或者销毁这个类的时候自动加载__destruct这个方法
    public function __destruct() {
        echo '<pre class="brush:php;toolbar:false">';
        var_dump(self::$link);
        mysql_close(self::$link);
        var_dump(self::$link);
    }

}

$mysql = new Example('localhost', 'root', 'root', 'test');
Copy after login

result:

resource(2) of type (mysql link)
resource(2) of type (Unknown)
Copy after login


The above introduces the PHP magic method: __construct __destruct, including the content of PHP magic method. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template