zoukankan      html  css  js  c++  java
  • 构造函数

    http://www.cnblogs.com/-simon/p/5887467.html

    PHP5可以在类中使用__construct()定义一个构造函数,具有构造函数的类,会在每次对象创建的时候调用该函数,因此常用来在对象创建的时候进行一些初始化工作。

    class Car {

       function __construct() {

           print "构造函数被调用 ";

       }

    }

    $car = new Car(); //实例化的时候 会自动调用构造函数__construct,这里会输出一个字符串

    在子类中如果定义了__construct则不会调用父类的__construct,如果需要同时调用父类的构造函数,需要使用parent::__construct()显式的调用。

    class Car {

       function __construct() {

           print "父类构造函数被调用 ";

       }

    }

    class Truck extends Car {

       function __construct() {

           print "子类构造函数被调用 ";

           parent::__construct();

       }

    }

    $car = new Truck();

    析构函数

    同样,PHP5支持析构函数,使用__destruct()进行定义,析构函数指的是当某个对象的所有引用被删除,或者对象被显式的销毁时会执行的函数。

    class Car {

       function __construct() {

           print "构造函数被调用  ";

       }

       function __destruct() {

           print "析构函数被调用  ";

       }

    }

    $car = new Car(); //实例化时会调用构造函数

    echo '使用后,准备销毁car对象  ';

    unset($car); //销毁时会调用析构函数

    当PHP代码执行完毕以后,会自动回收与销毁对象,因此一般情况下不需要显式的去销毁对象。

     
  • 相关阅读:
    npm ci fast install All In One
    WebGL & CG All In One
    StackOverflow winterbash 2021 All In One
    jira advanced searching All In One
    localStorage undefined bug All In One
    vcharts bug All In One
    crypto.getRandomValues & Math.random All In One
    Web 3D 技术 All In One
    企业微信如何设置用户当前状态 All In One
    parent.postMessage bug All In One
  • 原文地址:https://www.cnblogs.com/youxianyen/p/6337947.html
Copyright © 2011-2022 走看看