---
title: PHP Constructor
description: "## 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…"
url: "https://apprentice.mn/docs/php-constructor/"
updated: "2021-07-19"
category: PHP
---

# PHP Constructor

## 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();
?>`        [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fphp-constructor%2F&linkname=PHP%20Constructor](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fphp-constructor%2F&linkname=PHP%20Constructor)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fphp-constructor%2F&linkname=PHP%20Constructor](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fphp-constructor%2F&linkname=PHP%20Constructor)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fphp-constructor%2F&linkname=PHP%20Constructor](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fphp-constructor%2F&linkname=PHP%20Constructor)[https://www.addtoany.com/share](https://www.addtoany.com/share)
