我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。
我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?
我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。
我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?
当前回答
注意:如果子类定义了构造函数,父构造函数不会隐式调用。为了运行父构造函数,需要在子构造函数中调用parent::__construct()。如果子类没有定义构造函数,那么它可以像普通的类方法一样从父类继承(如果它没有声明为private)。
其他回答
它是用来声明构造函数的。
class Cat
{
function __construct()
{
echo 'meow';
}
}
每当创建类的新实例时,构造函数都会被调用,在这种情况下,构造函数将通过以下行调用:
$cat = new Cat();
在旧的PHP版本中,构造函数也可以使用类名来声明,例如:
class Cat
{
function Cat()
{
echo 'meow';
}
}
__construct方法用于在第一次创建对象时传入参数——这被称为“定义构造函数方法”,是一种常见的做法。
然而,构造函数是可选的——所以如果你不想在对象构造时传递任何参数,你就不需要它。
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);
有关什么是构造函数的更多细节,请参阅手册。
__construct只是简单地启动一个类。假设您有以下代码;
Class Person {
function __construct() {
echo 'Hello';
}
}
$person = new Person();
//the result 'Hello' will be shown.
我们没有创建另一个函数来响应单词“Hello”。它只是表明关键字__construct在初始化类或对象时非常有用。
__construct是在PHP5中引入的,它是定义你的构造函数的正确方法(在PHP4中,你使用类的名称作为构造函数)。 你不需要在你的类中定义构造函数,但是如果你想在对象构造中传递任何参数,那么你就需要一个构造函数。
一个例子是这样的:
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手册中解释了:点击这里
__construct是一个在使用新对象之前初始化它的方法。 http://php.net/manual/en/language.oop5.decon.php#object.construct