LoginSignup
0
1

More than 3 years have passed since last update.

PHPのOOPについて自習したことをまとめてみる②(__construct, __destruct について)

Posted at

__construct関数の使い方

construct.php
<?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();
?>

・set_〇〇関数が必要なくなるので、コード量が減る。

__destruct関数の使い方

destruct.php
<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function __destruct() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
  }
}

$apple = new Fruit("Apple", "red");
?>

・デストラクタは、オブジェクトが破壊されるか、スクリプトが停止または終了すると呼び出されます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1