【PHP】构造函数

依然范儿特西
2019-07-15 / 0 评论 / 1,175 阅读 / 正在检测是否收录...
  • 1、构造方法 __construct()
    主要用来在创建对象时初始化对象,向对象成员变量赋予初始值,在创建对象的语句中与 new 运算符一起使用。
  • 2、析构方法 __destruct()
    析构函数(destruct) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。
  • 3、PHP 不会在子类的构造方法中自动的调用父类的构造方法。要执行父类的构造方法,需要在子类的构造方法中调用 parent::__construct() 。
单独使用代码示例

class FOO {
    private $a, $b;
    public function __construct() {
        $this->a = 1;
        $this->b = 2;
    }
    public function test() {
        echo 'This is the method test of class FOO<br />';
        echo '$this->a=', $this->a, ', $this->b=', $this->b;
    }
}
$bar = 'FOO';
$foo = new $bar();
$foo->test()

配合使用代码示例

 
class maxbox
    {
        var $name;

        //构造函数
        function __construct()
        {
            $this->name = '第一个盒子';
        }

        //析构函数
        function __destruct()
        {
            $this->name = '第二个盒子';
        }

    }
    class box extends maxbox
    {
        public $width = '100px';
        public $height = '200px';

        //构造函数
        function __construct($w,$h)
        {
            //调用父类构造/析构方法
            parent::__construct();
            parent::__destruct();

            $this->width = $w;
            $this->height = $h;

            //输出父类的属性值
            echo $this->name;
        }

        public function setWH($w,$h)
        {
            $this->width = $w;
            $this->height = $h;
        }

        //析构函数
        function __destruct()
        {
            echo '执行完毕';
            echo $this->width = 0;
            echo $this->height = 0;
        }
    }
    $box = new box('400px','500px');
    echo $box->width;
    echo $box->height;
    $box->setWH('800px','900px');
    echo $box->width;
    echo $box->height;

0

评论 (0)

取消