What is the function __construct used for?(__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 函数是做什么用的?


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01