您现在的位置是:网站首页>软件开发>语言基础>PHPPHP

PHP魔术方法集—-__construct()

风口下的猪2019-06-09PHP

简介

一.定义

__construct()  - 在每次创建新对象时先调用此方法

 

二.使用注意事项

经过自己测试,一个PHP类里不能有多个构造方法,包括有参和无参,只能写其中一个,写多个就会报错。如果你只写一个无参数的构造方法,你实例化时后面带参数,依然会调用无参的构造方法。

 

三.表示方式

public function __construct()
{

}

public function 类名()
{

}

一般建议用第一种,用第二种的话,那么一个类就可以写2个构造方法,也只能写2个,这两个构造方法就是上面的2种形式,而且会优先调用第一种形式。

 

四.例子说明

<?php
/**
 * 清晰的认识__construct()
 */
class Example {
    public static $link;
    //在类实例化的时候自动加载__construct这个方法
    public function __construct($localhost$username$password$db) {
        self::$link = mysql_connect($localhost$username$password);
        if (mysql_errno()) {
            die('错误:' . mysql_error());
        }
        mysql_set_charset('utf8');
        mysql_select_db($db);
    }
    /**
     * 通过__construct链接好数据库然后执行sql语句......
     */
$mysql new Example('localhost''root''root''test');

 五.扩展

在使用__construct()时,一般和parent::__construct()一起使用。即调用父类的构造函数。使父类在被实例化时,执行该方法。

例如:

class Common extends Controller
{
publicfunction__construct( Request$request=null){
parent::__construct($request);
//执行登录验证
//相当于SESSION['admin']['admin_id']
if(!session('admin.admin_id')){
$this->redirect('admin/login/login');
}
}
}

很赞哦! (0)

上一篇:exit() 函数

下一篇:::作用域运算符

  • 软件开发
  • 素质要求
  • 计算机基础
  • 架构
  • 安全
  • 性能
  • 运维
  • 尾页
  • 数据库
  • 开发终端
  • 语言基础
  • 项目管理
  • 产品设计
  • 系统
  • 工作规范
  • 计算机网络
  • 前端技术栈
  • 数据结构
  • 计算机组成原理
  • 后端技术栈
  • 性能优化
  • 安全设计
  • 常见模块
  • 计算机操作系统
  • 服务器
  • python
  • MySQL
  • thinkphp
  • PHP
  • Java
  • JavaScript
  • Windows
  • Linux
  • 特效
  • indexedDB
  • vue
  • 淘宝联盟
  • Ionic
  • Angular
  • 微信小程序
  • 支付宝小程序
  • uni-app
  • css/sass/less
  • 支付
  • socket
  • 爬虫
  • web性能优化
  • 消息推送
  • CVM
  • sqlite
  • Redis
  • 前端基础
  • 基础
  • element
  • Nginx
  • yii2
  • /ponder/index.php/index/catelist/catelist/cateid/10.html

    相关阅读 (同一栏目)

    << /

    标签云

    站点信息

    • 文章统计:528篇
    • 移动端访问:扫码进入SQ3R