[php] What is the function __construct used for?

I have been noticing __construct a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP.

I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP?

This question is related to php constructor

The answer is


I think this is important to the understanding of the purpose of the constructor.
Even after reading the responses here it took me a few minutes to realise and here is the reason.
I have gotten into a habit of explicitly coding everything that is initiated or occurs. In other words this would be my cat class and how I would call it.

class_cat.php

class cat {
    function speak() {
        return "meow";  
    }
}

somepage.php

include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;

Where in @Logan Serman's given "class cat" examples it is assumed that every time you create a new object of class "cat" you want the cat to "meow" rather than waiting for you to call the function to make it meow.

In this way my mind was thinking explicitly where the constructor method uses implicity and this made it hard to understand at first.


The __construct method is used to pass in parameters when you first create an object--this is called 'defining a constructor method', and is a common thing to do.

However, constructors are optional--so if you don't want to pass any parameters at object construction time, you don't need it.

So:

// Create a new class, and include a __construct method
class Task {

    public $title;
    public $description;

    public function __construct($title, $description){
        $this->title = $title;
        $this->description = $description;
    }
}

// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');

// Try it and see
var_dump($task->title, $task->description);

For more details on what a constructor is, see the manual.


__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.

    class Test
    {
      function __construct($value1,$value2)
      {
         echo "Inside Construct";
         echo $this->value1;
         echo $this->value2;
      }
    }

//
  $testObject  =  new Test('abc','123');

__construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.

class Person {

    public function __construct() {
        // Code called for each new Person we create
    }

}

$person = new Person();

A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.

class Person {

    public $name = '';

    public function __construct( $name ) {
        $this->name = $name;
    }

}

$person = new Person( "Joe" );
echo $person->name;

Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.

Note: I retrieved this from the log of the (at time of this writing) accepted answer.


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.

https://www.w3schools.com/php/php_oop_constructor.asp


__construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.

class Person {

    public function __construct() {
        // Code called for each new Person we create
    }

}

$person = new Person();

A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.

class Person {

    public $name = '';

    public function __construct( $name ) {
        $this->name = $name;
    }

}

$person = new Person( "Joe" );
echo $person->name;

Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.

Note: I retrieved this from the log of the (at time of this writing) accepted answer.


__construct simply initiates a class. Suppose you have the following code;

Class Person { 

 function __construct() {
   echo 'Hello';
  }

}

$person = new Person();

//the result 'Hello' will be shown.

We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.


I think this is important to the understanding of the purpose of the constructor.
Even after reading the responses here it took me a few minutes to realise and here is the reason.
I have gotten into a habit of explicitly coding everything that is initiated or occurs. In other words this would be my cat class and how I would call it.

class_cat.php

class cat {
    function speak() {
        return "meow";  
    }
}

somepage.php

include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;

Where in @Logan Serman's given "class cat" examples it is assumed that every time you create a new object of class "cat" you want the cat to "meow" rather than waiting for you to call the function to make it meow.

In this way my mind was thinking explicitly where the constructor method uses implicity and this made it hard to understand at first.


I believe that function __construct () {...} is a piece of code that can be reused again and again in substitution for TheActualFunctionName () {...}. If you change the CLASS Name you do not have to change within the code because the generic __construct refers always to the actual class name...whatever it is. You code less...or?


The constructor is a method which is automatically called on class instantiation. Which means the contents of a constructor are processed without separate method calls. The contents of a the class keyword parenthesis are passed to the constructor method.


class Person{
 private $fname;
 private $lname;

 public function __construct($fname,$lname){
  $this->fname = $fname;
  $this->lname = $lname;
 }
}
$objPerson1 = new Person('john','smith');

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).


__construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.

class Person {

    public function __construct() {
        // Code called for each new Person we create
    }

}

$person = new Person();

A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.

class Person {

    public $name = '';

    public function __construct( $name ) {
        $this->name = $name;
    }

}

$person = new Person( "Joe" );
echo $person->name;

Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.

Note: I retrieved this from the log of the (at time of this writing) accepted answer.


__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.

    class Test
    {
      function __construct($value1,$value2)
      {
         echo "Inside Construct";
         echo $this->value1;
         echo $this->value2;
      }
    }

//
  $testObject  =  new Test('abc','123');

I Hope this Help:

<?php
    // The code below creates the class
    class Person {
        // Creating some properties (variables tied to an object)
        public $isAlive = true;
        public $firstname;
        public $lastname;
        public $age;

        // Assigning the values
        public function __construct($firstname, $lastname, $age) {
          $this->firstname = $firstname;
          $this->lastname = $lastname;
          $this->age = $age;
        }

        // Creating a method (function tied to an object)
        public function greet() {
          return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
        }
      }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    // Printing out, what the greet method returns
    echo $me->greet(); 
    ?>

For More Information You need to Go to codecademy.com


The __construct method is used to pass in parameters when you first create an object--this is called 'defining a constructor method', and is a common thing to do.

However, constructors are optional--so if you don't want to pass any parameters at object construction time, you don't need it.

So:

// Create a new class, and include a __construct method
class Task {

    public $title;
    public $description;

    public function __construct($title, $description){
        $this->title = $title;
        $this->description = $description;
    }
}

// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');

// Try it and see
var_dump($task->title, $task->description);

For more details on what a constructor is, see the manual.


class Person{
 private $fname;
 private $lname;

 public function __construct($fname,$lname){
  $this->fname = $fname;
  $this->lname = $lname;
 }
}
$objPerson1 = new Person('john','smith');

I believe that function __construct () {...} is a piece of code that can be reused again and again in substitution for TheActualFunctionName () {...}. If you change the CLASS Name you do not have to change within the code because the generic __construct refers always to the actual class name...whatever it is. You code less...or?


I Hope this Help:

<?php
    // The code below creates the class
    class Person {
        // Creating some properties (variables tied to an object)
        public $isAlive = true;
        public $firstname;
        public $lastname;
        public $age;

        // Assigning the values
        public function __construct($firstname, $lastname, $age) {
          $this->firstname = $firstname;
          $this->lastname = $lastname;
          $this->age = $age;
        }

        // Creating a method (function tied to an object)
        public function greet() {
          return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
        }
      }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    // Printing out, what the greet method returns
    echo $me->greet(); 
    ?>

For More Information You need to Go to codecademy.com


Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).


Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

The constructor is a method which is automatically called on class instantiation. Which means the contents of a constructor are processed without separate method calls. The contents of a the class keyword parenthesis are passed to the constructor method.


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.

https://www.w3schools.com/php/php_oop_constructor.asp


__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct


Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

__construct simply initiates a class. Suppose you have the following code;

Class Person { 

 function __construct() {
   echo 'Hello';
  }

}

$person = new Person();

//the result 'Hello' will be shown.

We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.


__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct


Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();