PHP Constructor

1 min read

PHP – The __construct Function #

A constructor allows you to initialize an object’s properties upon creation of the object.

Байгуулагч нь объектыг бий болгосноор объектын шинж чанарыг эхлүүлэх боломжийг олгодог.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Хэрэв та __construct()  функцийг үүсгэсэн бол ангиас объект үүсгэх үед PHP энэ функцийг автоматаар дуудах болно.

Notice that the construct function starts with two underscores (__)!

Барилгын функц нь хоёр доогуур зураас (__) -аас эхэлдэг болохыг анхаарна уу!

We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:

Доорх жишээн дээр байгуулагчийг ашиглах нь set_name () аргыг дуудахаас аварч, кодын хэмжээг бууруулдаг болохыг бид харж байна.

Example #

Жишээ #

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

Another example:

Өөр жишээ:

Example #

Жишээ #

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

Powered by BetterDocs

Leave a Reply