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

ژوئیه 09, 2024 4 mins read

وقتی یک شی را ایجاد می‌کنیم می توانیم به وسیله constructor یا سازنده، متغیرها را مقداردهی اولیه کنیم.

__construct()

اگر از این تابع استفاده کنیم دیگر نیازی به استفاده از 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

__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”);
?>
Image NewsLetter
Icon primary
Newsletter

در خبرنامه آرتا رسانه عضو شوید

با آخرین اخبار و تخفیف های ما آگاه شوید