PHP OOP - Constructor

What is a Constructor in PHP?


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


A constructor is a special method in a class that is automatically called when a new object of the class is created.


In PHP, constructors are defined using the __construct() method.


Syntax of a Constructor


class ClassName {
  public function __construct() {
    // Code that runs when an object is created
  }
}



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


<?php
class Car {
public $brand;
public $color;
// Constructor
function __construct($brand) {
$this->brand = $brand;
}

// Methods
public function get_brand() {
return $this->brand;
}
}
// Creating objects with constructor
$car = new Car("Honda");
echo $car->get_brand(); // Output: This is a Honda.
?>

Try it yourself

Another example:

<?php
class Car {
public $brand;
public $color;
// Constructor
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
// Methods
public function get_brand() {
return $this->brand;
}
public function get_color() {
return $this->color;
}
}
// Creating objects with constructor
$car = new Car("Honda","Blue");

echo "Brand:" . $car->get_brand();
echo "<br>";
echo "Color:" . $car->get_color();
?>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.