__construct使用的函数是什么? [英] What is the function __construct used for?
问题描述
我一直注意到 __ construct
很多类。我做了一些阅读和网上冲浪,但我找不到一个解释,我可以理解。我刚刚开始与OOP。
我想知道是否有人可以给我一个一般的想法是什么,然后一个简单的例子,如何使用PHP ?
__construct是PHP5中引入的,它是定义你的构造函数的正确方法你使用类的名称为构造函数)。
你不需要在你的类中定义一个构造函数,但是如果你想传递任何参数对象构造,那么你需要一个。
这样:
类数据库{
protected $ userName;
protected $ password;
protected $ dbName;
public function __construct($ UserName,$ Password,$ DbName){
$ this-> userName = $ UserName;
$ this-> password = $ Password;
$ this-> dbName = $ DbName;
}
}
//你可以这样使用:
$ db = new Database('user_name','password','database_name');所有其他都在PHP手册中解释:点击这里
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.
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?
解决方案 The "__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' );
Everything else is explained in the PHP manual: click here
这篇关于__construct使用的函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!