PHP oops - Constructor

What is PHP oops - Constructor?

A constructor is a method defined inside a class which is called automatically when object is created.

A constructor is used to initialize the object.

You can define constructor by using __construct function.

A Constructor is automatically executed when object is Created.

Constructor have arguments.

A constructor doen't return any value.

PHP doesn't support function overloading So, we cannot have multiple implementations for constructor in a class.

Constructor types:

There are three type of constructor.

  1. Default Constructor: It doen't have parameters, but the values to the default constructor can be passed dynamically.
  2. Parameterized Constructor: It has many number of parameters.
  3. Copy Constructor: It accepts the address of the other objects as a parameter.

PHP Syntax:

function __construct ([ mixed $args = "" [, $... ]] )

PHP Example :

<?php
// code by aryatechno!
class Course
{
    function __construct()
    {
        echo "Learn php Course at aryatechno!";
    }
}

$learn = new Course;

?>

Output:
Learn php Course at aryatechno!

Explaination :  As above example , When $learn object is created, Constructor is called automatically.

Constructor with arguments

Constructor can pass arguments as per as below example.

PHP Example :

<?php
// code by aryatechno!
class Course
{
    public $name;
    function __construct($name)
    {
        $this->name=$name;
    }
    function display()
    {
        echo "Learn $this->name at aryatechno!";
    }
    
}

$learn = new Course("PHP Constructor");
$learn->display();
?>

Output:

Learn PHP Constructor at aryatechno!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

53219