PHP 构造函数

创建于 2024-12-03 / 28
字体: [默认] [大] [更大]

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();
?> 亲自试一试 »

0 人点赞过