>  기사  >  백엔드 개발  >  PHP 魔术方法 __construct __destruct (一),phpdestruct_PHP教程

PHP 魔术方法 __construct __destruct (一),phpdestruct_PHP教程

WBOY
WBOY원래의
2016-07-13 10:13:181540검색

PHP 魔术方法 __construct __destruct (一),phpdestruct

慢慢长寻夜,明月高空挂

__construct()  - 在每次创建新对象时先调用此方法

__destruct()   - 对象的所有引用都被删除或者当对象被显式销毁时执行

<?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');

结果:

resource(2) of type (mysql link)
resource(2) of type (Unknown)

  

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/916824.htmlTechArticlePHP 魔术方法 __construct __destruct (一),phpdestruct 慢慢长寻夜,明月高空挂 __construct() - 在每次创建新对象时先调用此方法 __destruct() -对象的所...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.