search icon

__construct – PHP

__construct er en indbygget metode i klasser i PHP. Den kaldes så snart der laves et objekt af klassen. I eksemplet herunder bruges den til, at indsætte data i properties.

<?php
  class Car{
    //Properties
    private $brand;
    private $model;
    private $color;

    //__construct-metoden
    function __construct($carBrand, $carModel, $carColor){
      $this->brand = $carBrand;
      $this->model = $carModel;
      $this->color = $carColor;
    }
  }

  $myCar = new Car("Hyundai", "i30", "Black");

Skriv et svar

Verified by MonsterInsights