آرتا رسانه

آموزش برنامه نویسی PHP-جلسه شانزدهم

__construct()

وقتی یک شی را ایجاد می‌کنیم می توانیم به وسیله constructor یا سازنده، متغیرها را مقداردهی اولیه کنیم. اگر از این تابع استفاده کنیم دیگر نیازی به استفاده از 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();
?<

__destruct Function()

این تابع مقابل تابع کانستراکت عمل می کند یعنی مخرب است و اگر بخواهیم کلاسی را بعد از اینکه کارمان با اون تموم شد حذف کنیم از این تابع استفاده می کنیم.

<?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”);
?>

آرتا رسانه
آرتا رسانه
دیجیتال مارکتینگ چیست؟
Loading
/
پیمایش به بالا