我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。
我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?
我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。
我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?
当前回答
__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()是构造函数的方法名。构造函数在对象创建后被调用,是放置初始化代码等的好地方。
class Person {
public function __construct() {
// Code called for each new Person we create
}
}
$person = new Person();
构造函数可以以正常的方式接受参数,这些参数是在创建对象时传递的。
class Person {
public $name = '';
public function __construct( $name ) {
$this->name = $name;
}
}
$person = new Person( "Joe" );
echo $person->name;
与其他一些语言(如Java)不同,PHP不支持重载构造函数(即拥有多个接受不同参数的构造函数)。您可以使用静态方法来实现此效果。
注意:我从(在撰写本文时)接受的答案的日志中检索到这个。
构造函数是一个在类实例化时自动调用的方法。这意味着构造函数的内容不需要单独的方法调用就可以处理。类关键字括号的内容被传递给构造函数方法。
__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手册中解释了:点击这里
我认为这对于理解构造函数的目的很重要。 即使在阅读了这里的回复后,我也花了几分钟才意识到这是原因。 我已经养成了一个习惯,即显式地编码所有启动或发生的事情。换句话说,这将是我的猫类,我将如何称呼它。
class_cat.php
class cat {
function speak() {
return "meow";
}
}
somepage.php
include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;
在@Logan Serman给出的“类猫”的例子中,假设每次你创建一个类“猫”的新对象时,你都希望猫“喵”,而不是等待你调用函数让它喵。
通过这种方式,我的大脑在明确地思考构造函数方法使用隐式的地方,这使得它一开始很难理解。
注意:如果子类定义了构造函数,父构造函数不会隐式调用。为了运行父构造函数,需要在子构造函数中调用parent::__construct()。如果子类没有定义构造函数,那么它可以像普通的类方法一样从父类继承(如果它没有声明为private)。