php __construct 函数是做什么用的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/455910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the function __construct used for?
提问by Levi
I have been noticing __constructa 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.
我在__construct课堂上注意到了很多。我做了一些阅读和网上冲浪,但我找不到我能理解的解释。我刚刚开始使用 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?
我想知道是否有人可以让我大致了解它是什么,然后是一个如何与 PHP 一起使用的简单示例?
回答by Jan Han?i?
__constructwas 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.
__construct是在 PHP5 中引入的,它是定义构造函数的正确方法(在 PHP4 中,您使用类的名称作为构造函数)。你不需要在你的类中定义一个构造函数,但是如果你希望在对象构造上传递任何参数,那么你需要一个。
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
PHP手册中解释了其他所有内容:单击此处
回答by Rob
__construct()is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.
__construct()是构造函数的方法名称。构造函数在对象创建后被调用,是放置初始化代码等的好地方。
class Person {
public function __construct() {
// Code called for each new Person we create
}
}
$person = new Person();
A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.
构造函数可以以正常方式接受参数,这些参数是在创建对象时传递的,例如
class Person {
public $name = '';
public function __construct( $name ) {
$this->name = $name;
}
}
$person = new Person( "Joe" );
echo $person->name;
Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.
与某些其他语言(例如 Java)不同,PHP 不支持重载构造函数(即,具有多个接受不同参数的构造函数)。您可以使用静态方法实现此效果。
Note: I retrieved this from the log of the (at time of this writing) accepted answer.
注意:我从(在撰写本文时)接受的答案的日志中检索到了这个。
回答by Logan Serman
Its another way to declare the constructor. You can also use the class name, for ex:
它是另一种声明构造函数的方法。您还可以使用类名,例如:
class Cat
{
function Cat()
{
echo 'meow';
}
}
and
和
class Cat
{
function __construct()
{
echo 'meow';
}
}
Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:
是等价的。每当创建类的新实例时都会调用它们,在这种情况下,将使用以下行调用它们:
$cat = new Cat();
回答by ian
I think this is important to the understanding of the purpose of the constructor.
Even after reading the responses here it took me a few minutes to realise and here is the reason.
I have gotten into a habit of explicitly coding everything that is initiated or occurs. In other words this would be my cat class and how I would call it.
我认为这对于理解构造函数的目的很重要。
即使在阅读了这里的回复后,我还是花了几分钟才意识到,这就是原因。
我已经养成了对启动或发生的一切进行明确编码的习惯。换句话说,这将是我的猫课以及我会如何称呼它。
class_cat.php
class_cat.php
class cat {
function speak() {
return "meow";
}
}
somepage.php
某个页面.php
include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;
Where in @Logan Serman's given "class cat" examples it is assumed that every time you create a new object of class "cat" you want the cat to "meow" rather than waiting for you to call the function to make it meow.
在@Logan Serman 给出的“class cat”示例中,假设每次创建“cat”类的新对象时,您都希望猫“喵喵叫”,而不是等待您调用函数使其喵喵叫。
In this way my mind was thinking explicitly where the constructor method uses implicity and this made it hard to understand at first.
通过这种方式,我的思想明确地思考构造函数方法在哪里使用隐式,这使得一开始很难理解。
回答by Jimmy James
The constructor is a method which is automatically called on class instantiation. Which means the contents of a constructor are processed without separate method calls. The contents of a the class keyword parenthesis are passed to the constructor method.
构造函数是一个在类实例化时自动调用的方法。这意味着在没有单独的方法调用的情况下处理构造函数的内容。class 关键字括号的内容传递给构造函数方法。
回答by James
The __constructmethod is used to pass in parameters when you firstcreate an object--this is called 'defining a constructor method', and is a common thing to do.
该__construct方法用于在您第一次创建对象时传入参数——这称为“定义构造函数方法”,并且是一种常见的做法。
However, constructors are optional--so if you don't want to pass any parameters at object construction time, you don't need it.
但是,构造函数是可选的——因此,如果您不想在对象构造时传递任何参数,则不需要它。
So:
所以:
// Create a new class, and include a __construct method
class Task {
public $title;
public $description;
public function __construct($title, $description){
$this->title = $title;
$this->description = $description;
}
}
// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');
// Try it and see
var_dump($task->title, $task->description);
For more details on what a constructor is, see the manual.
有关什么是构造函数的更多详细信息,请参阅手册。
回答by Zaman
I Hope this Help:
我希望这有助于:
<?php
// The code below creates the class
class Person {
// Creating some properties (variables tied to an object)
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
// Assigning the values
public function __construct($firstname, $lastname, $age) {
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
// Creating a method (function tied to an object)
public function greet() {
return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
}
}
// Creating a new person called "boring 12345", who is 12345 years old ;-)
$me = new Person('boring', '12345', 12345);
// Printing out, what the greet method returns
echo $me->greet();
?>
For More Information You need to Go to codecademy.com
有关更多信息,您需要访问codecademy.com
回答by Hussein
class Person{
private $fname;
private $lname;
public function __construct($fname,$lname){
$this->fname = $fname;
$this->lname = $lname;
}
}
$objPerson1 = new Person('john','smith');
回答by yasir kk
__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.
__construct 在创建新对象时总是被调用,或者在初始化发生时被调用。它适用于对象在使用之前可能需要的任何初始化。__construct 方法是在类中执行的第一个方法。
class Test
{
function __construct($value1,$value2)
{
echo "Inside Construct";
echo $this->value1;
echo $this->value2;
}
}
//
$testObject = new Test('abc','123');
回答by Seyedan
__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct
__construct 是一种在新对象使用前对其进行初始化的方法。
http://php.net/manual/en/language.oop5.decon.php#object.construct

