Home  >  Article  >  Backend Development  >  PHP的构造方法,析构方法和this关键字详细介绍_PHP

PHP的构造方法,析构方法和this关键字详细介绍_PHP

WBOY
WBOYOriginal
2016-06-01 11:59:30717browse

一.什么是构造方法
    构造方法是类的一种特殊的方法,它的主要作用是完成对新对象初始化.
    特点:
1.    没有返回值.
2.    在创建一个新的对象时,系统会自动调用该类的构造方法完成对新对角的初始化.
    语法:
    php5:        修饰符 function __construct()

                        {
                            //code

                        }
    php4:        修饰符 function 类名()

                        {
                            //code

                        }
注意:
   1. php5里对两者都支持,如果两种构造方法同时存在的话,优先选择第一种.
   2. 一个类里面默认有一个不带参数为空的构造方法,一旦自定义了一个构造方法,就会覆盖默认的构造方法.

      所以说一个类有且只有一个构造方法.
   3.一个类只能有一个构造方法.(不能重载)
   4.构造方法默认的访问修饰符为public.
二.this关键字
    this代表当前对象.可以理解为:谁调用它,它就代表谁.
    注意事项:
    this不在类定义的使用,只能在类定义的方法中使用.
三.实例
复制代码 代码如下:
    header("Conter-Type:text/html;charset=utf-8");
    class Person
    {
        public $name;  //成员变量
        public $age;

       // function __construct()
        //{
          //  echo "不带参数的构造方法";

        /

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn