zoukankan      html  css  js  c++  java
  • PHP 魔术方法 __construct __destruct (一)

    慢慢长寻夜,明月高空挂

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

      

  • 相关阅读:
    正则匹配
    去除数组、对象某个元素
    换行
    a标签问题
    vue的坑
    宽度100%-20px ,css样式设置超出部分...
    搜狗密码框自带小键盘问题
    阻止button刷新页面
    Java IO流经典练习题
    Java中统计字符串中各个字符出现的次数
  • 原文地址:https://www.cnblogs.com/uduemc/p/4117824.html
Copyright © 2011-2022 走看看