PHP OOP - 构造函数
PHP - __construct 函数
构造函数允许您在创建对象时初始化对象的属性。
如果您创建一个 __construct()
函数,当您从类中创建一个对象时,PHP 将自动调用此函数。
请注意,构造函数以两个下划线(__
)开头!
我们在下面的例子中看到,使用构造函数可以节省我们调用 set_name()
方法的步骤,从而减少了代码量:
实例
<?php class Fruit { public $name; public $color; function __construct($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit("Apple"); echo $apple->get_name(); ?>
另一个例子:
实例
<?php class Fruit { public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } function get_name() { return $this->name; } function get_color() { return $this->color; } } $apple = new Fruit("Apple", "red"); echo $apple->get_name(); echo "<br>"; echo $apple->get_color(); ?>