__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
相关文章