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

    在最近自己写的PHP小程序中遇到了如何使用PHP构造函数的情况,在PHP中允许我们在一个类中定义一个构造函数 如:

    <?php
    class User
    {
        public $name;
    
        function User()
        {
            $this->name="shaonian";
        }
    
        function Do()
        {
            $a=$this->name;
            //...
        }
    }
    ?>

    或者使用最新的 __construct() ,无论类名是什么,构造函数都为__construct()

    <?php
    class User
    {
        public $name;
    
        function __construct()
        {
            $this->name="shaonian";
        }
    
        function Do()
        {
            $a=$this->name;
            //...
        }
    }
    ?>

    注意 对类属性进行复制和调用时,$符号一定要加载this前面,而不是属性名前面。另外,PHP中的构造函数不会隐式调用父类的构造函数,如果要调用父类的构造函数,需要显示的调用parent::__construct(),如:

    <?php
    class Person
    {
        public $gender;
        function __construct()
        {
            $this->gender='male';
        }
    }
    
    
    class User extends Person
    {
        public $name;
    
        function __construct()
        {
            parent::__construct();
            $this->name="shaonian";
        }
    
        function Do()
        {
            $a=$this->name;
            //...
        }
    }
    ?>
  • 相关阅读:
    尝试一下搭博客
    python IO
    python OOP
    杂笔记
    codeforces 217E 【Alien DNA】
    dfs序七个经典问题(转)
    poj 1945 Power Hungry Cows A*
    NOIP 2012 洛谷P1081 开车旅行
    洛谷 P1924 poj 1038
    poj 2176 folding
  • 原文地址:https://www.cnblogs.com/dreamtecher/p/5024461.html
Copyright © 2011-2022 走看看