问题描述
我已经注意到 __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 函数是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)