zoukankan      html  css  js  c++  java
  • php构造函数实例讲解

    PHP官网定义:

    复制代码 代码如下:

    构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用。当函数与类同名时,这个函数将成为构造函数。如果一个类没有构造函数,则调用基类的构造函数,如果有的话,则调用自己的构造函数


    如a.php一个class a类:

    复制代码 代码如下:

    <?php
    class a{
     function __construct(){
      echo 'class a';
     }
    }


    b.php有个class b类继承a类:

    复制代码 代码如下:

    <?php
    include 'a.php';
    class b extends a{
     function __construct(){
      echo '666666';
      //parent::__construct();
     }

     function index(){
      echo 'index';
     }
    }
     


    $test=new b();
    这样写的话,b类有自己的构造函数,那么实例化b类的时候,自动运行构造函数,此时默认不运行父类的构造函数,如果同时要运行父类构造函数,要声明parent::__construct();

    复制代码 代码如下:

    <?php
    include 'a.php';
    class b extends a{
     function index(){
      echo 'index';
     }
    }
     


    $test=new b();
    此时b类没有自己的构造函数,那么将默认执行父类的构造函数。

  • 相关阅读:
    内存分配问题
    C++ assert 的一点说明
    强大的stringstream
    C++中随机数
    C++ 中new
    C++ 中string 详解 转载自 博客园
    未命名名字空间
    使用ifstream和getline读取文件内容[c++]
    6.bootstrap练习笔记-缩略图和list-group
    3.bootstrap练习笔记-媒体内容
  • 原文地址:https://www.cnblogs.com/gaogaoxingxing/p/5977197.html
Copyright © 2011-2022 走看看