What is the function __construct used for?

PhpConstructor

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

__construct was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.

An example could go like this:

class Database {
  protected $userName;
  protected $password;
  protected $dbName;

  public function __construct ( $UserName, $Password, $DbName ) {
    $this->userName = $UserName;
    $this->password = $Password;
    $this->dbName = $DbName;
  }
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

Everything else is explained in the PHP manual: click here

Solution 2 - Php

__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.

Solution 3 - Php

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();

Solution 4 - Php

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.

Solution 5 - Php

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.

Solution 6 - Php

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.

Solution 7 - Php

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

Solution 8 - Php

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

Solution 9 - Php

__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');

Solution 10 - Php

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?

Solution 11 - Php

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

Solution 12 - Php

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).

Solution 13 - Php

__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.

Solution 14 - Php

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

Solution 15 - Php

Let me explain __construct() without first using the method ... One thing to know about __construct() is that it is an inbuilt function, well let me call it method in PHP. Just as we have print_r() for procedural, the __construct() is an inbuilt for OOP.

That being said, let's explore why you should use this function called __construct().

  /*=======Class without __construct()========*/
  class ThaddLawItSolution
   {
      public $description;
      public $url;
      public $ourServices;

      /*===Let us initialize a value to our property via the method set_name()==== */
     public function setName($anything,$anythingYouChoose,$anythingAgainYouChoose)
     {
      $this->description=$anything;
      $this->url=$anythingYouChoose;
      $this->ourServices=$anythingAgainYouChoose;
    }
    /*===Let us now display it on our browser peacefully without stress===*/
    public function displayOnBrowser()
    {
       echo "$this->description is a technological company in Nigeria and our domain name is actually $this->url.Please contact us today for our services:$this->ourServices";
    }
 
 }

         //Creating an object of the class ThaddLawItSolution
$project=new ThaddLawItSolution;
        //=======Assigning Values to those properties via the method created====//
$project->setName("Thaddlaw IT Solution", "https://www.thaddlaw.com", "Please view our website");
      //===========Let us now display it on the browser=======
$project->displayOnBrowser();

__construct() makes life for you very easy, imaging the time it took me to assigning values to those properties via that method. From the code above, I created an object which is first and then assign values to the properties which is second before finally showing it on the browser. But using __construct() while creating an object i.e. $project= new ThaddLawItSolution; you would do what you did for assigning values to that method immediately while creating the object, i.e.

$project=new ThaddLawItSolution("Thaddlaw IT Solution", "https://www.thaddlaw.com","Please view our website");

//===Let's now use __constructor=====

Just remove that method called setName and put __construct(); and when creating an object, you assign the values at once. That is the point behind the whole __construct() method. But note that this is an inbuilt method or function

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeviView Question on Stackoverflow
Solution 1 - PhpJan HančičView Answer on Stackoverflow
Solution 2 - PhpRobView Answer on Stackoverflow
Solution 3 - PhpLogan SermanView Answer on Stackoverflow
Solution 4 - PhpianView Answer on Stackoverflow
Solution 5 - PhpJimmy JamesView Answer on Stackoverflow
Solution 6 - PhpJamesView Answer on Stackoverflow
Solution 7 - PhpZamanView Answer on Stackoverflow
Solution 8 - PhpHusseinView Answer on Stackoverflow
Solution 9 - Phpyasir kkView Answer on Stackoverflow
Solution 10 - PhpwalterView Answer on Stackoverflow
Solution 11 - PhpNegView Answer on Stackoverflow
Solution 12 - PhpVigneshView Answer on Stackoverflow
Solution 13 - PhpHarrisView Answer on Stackoverflow
Solution 14 - Phpبلال اصغرView Answer on Stackoverflow
Solution 15 - PhpGodswillView Answer on Stackoverflow