PHP(十一)构造函数

1、构造方法 __construct()
主要用来在创建对象时初始化对象,向对象成员变量赋予初始值,在创建对象的语句中与 new 运算符一起使用。
2、析构方法 __destruct()
析构函数(destruct) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。
3、PHP 不会在子类的构造方法中自动的调用父类的构造方法。要执行父类的构造方法,需要在子类的构造方法中调用 parent::__construct() 。
列:

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('300px','500px');
    echo $box->width;
    echo $box->height;
    $box->setWH('600px','700px');
    echo $box->width;
    echo $box->height;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值