沃梦达 / 编程问答 / php问题 / 正文

__construct 函数是做什么用的?

What is the function __construct used for?(__construct 函数是做什么用的?)

本文介绍了__construct 函数是做什么用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注意到 __construct 很多关于类.我做了一些阅读和网上冲浪,但我找不到我能理解的解释.我刚开始接触 OOP.

I have been noticing __construct a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP.

我想知道是否有人可以让我大致了解它是什么,然后是一个如何与 PHP 一起使用的简单示例?

I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP?

推荐答案

__construct 是在 PHP5 中引入的,它是定义构造函数的正确方法(在 PHP4 中你使用了构造函数的类).您不需要在类中定义构造函数,但是如果您希望在对象构造中传递任何参数,那么您需要一个.

__construct was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.

一个例子可能是这样的:

An example could go like this:

class Database {
  protected $userName;
  protected $password;
  protected $dbName;

  public function __construct ( $UserName, $Password, $DbName ) {
    $this->userName = $UserName;
    $this->password = $Password;
    $this->dbName = $DbName;
  }
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

PHP 手册中解释了其他所有内容:点击此处

Everything else is explained in the PHP manual: click here

这篇关于__construct 函数是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:__construct 函数是做什么用的?

基础教程推荐