This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
In this article, we're going to discuss the basics of constructors in PHP. You'll learn the purpose of PHP constructors and how to use them.
What Is a Constructor?
Here's the official definition:
Constructors are ordinary methods which are called during the instantiation of their corresponding object. As such, they may define an arbitrary number of arguments, which may be required, may have a type, and may have a default value. Constructor arguments are called by placing the arguments in parentheses after the class name. PHP Manual: Constructors and Destructors
When you instantiate an object of any class, and if that class has defined the constructor method, it would be automatically called. If the constructor method has defined any mandatory arguments, you must pass those arguments as well when you instantiate an object of that class.
Let’s quickly see how a constructor method looks like in PHP.
<?php class tutsplus { public function __construct() { // you can initialize object properties here echo 'Hey, you have just instantiated a new object!'; } } $objTutsplus = new tutsplus(); // output: Hey, you have just instantiated a new object! ?>
So that’s how you can define a constructor in your class. You must define the __construct
method in your class, and it becomes the constructor method for your class. In the above example, whenever you instantiate the tutsplus
object, the __construct
method will be called first. It’s important to note that you must define a constructor method as public, you won't be able to instantiate an object of your class!
Prior to PHP 5, to define a constructor, you would use a function with the same name as the class it is defined in, and it would be treated as a constructor method! You might be familiar with this way of declaring constructors from other programming languages like C++. In PHP, they are called PHP4-style constructors, and it’s not recommended to use this style, since they are going to be deprecated sooner or later.
Let’s revise the previous example to see how the constructor would look in a previous version of PHP:
<?php class tutsplus { public function tutsplus() { // you can initialize object properties here echo 'Hey, you have just instantiated a new object!'; } } $objTutsplus = new tutsplus(); // output: Hey, you have just instantiated a new object! ?>
At the time of writing, this example still worked. Try it out!
What’s the Purpose of a Constructor?
Now you know how to declare a constructor method in PHP, but what is the use of a constructor method? That’s what we’ll discuss in this section with a couple of real-world examples.
Initializing Required Properties
The main purpose of a constructor method is to initialize an object's properties when it’s being created. The benefit of this approach is that you don’t have to call setter methods later on to initialize the object's properties after an object is created. So if you think that an object must have a few properties set, a constructor method is the way to go!
Let’s quickly go through the following example to understand how it works.
<?php class tutsplusAuthor { private $author_name; private $author_email; public function __construct($name, $email) { $this->author_name = $name; $this->author_email = $email; } public function getAuthorName() { return $this->author_name; } public function getAuthorEmail() { return $this->author_email; } } $objTutsplusAuthor = new tutsplusAuthor("John", "john@tutsplus.com"); echo $objTutsplusAuthor->getAuthorName(); echo $objTutsplusAuthor->getAuthorEmail(); ?>
As you can see, when the tutsplusAuthor
object is instantiated, the __construct
method is called. The __construct
method expects two arguments, and we’ve passed those two arguments when we create the new object: new tutsplusAuthor("John", "john@tutsplus.com")
. Finally, we’ve initialized the author_name
and author_email
properties to the corresponding values that are passed in the __construct
method. So in this way, you can initialize object properties with a constructor method.
If you tried to instantiate the tutsplusAuthor
object without passing any arguments, you would get a fatal error as shown in the following snippet.
<?php // try to instantiate tutsplusAuthor without arguments $objTutsplusAuthor = new tutsplusAuthor(); // output // PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function tutsplusAuthor::__construct(), 0 passed in /public_html/examples/constructor.php on line 24 and exactly 2 expected in /public_html/examples/constructor.php ?>
So you need to make sure that you pass any required arguments when instantiate the tutsplusAuthor
object.
Type-Checking Constructor Arguments
In fact, you can also do type checking as well if you want that the arguments must be of specific types.
<?php class tutsplusAuthor { ... ... public function __construct(string $name, string $email, array $hobbies) { $this->author_name = $name; $this->author_email = $email; $this->hobbies = $hobbies; } ... ... }
In the above example, you must pass the first two arguments of type string
and the last argument must be of type array
. If you passed a string value in the last argument, you would get the following error:
PHP Fatal error: Uncaught TypeError: Argument 3 passed to tutsplusAuthor::__construct() must be of the type array, string given
So that’s how you can do strict type checking with constructor arguments.
Initializing a Database Connection
Another use of a constructor is to do some I/O: for example, opening a file and starting to read its contents, beginning an API request, or creating a database connection.
Let’s look at a an example of a constructor that creates a database connection.
<?php class Database { private $host; private $user; private $password; private $dbname; private $connection; public function __construct($host, $user, $password, $dbname) { $this->host=$host; $this->user=$user; $this->password=$password; $this->dbname=$dbname; $this->connection = mysqli_connect($this->host, $this->user, $this->password, $this->dbname); if (!$this->connection) { die("connection failed: " . mysqli_connect_error()); } } // other DBAL methods } ?>
How to Call a Constructor of the Parent Class?
In this last section, we’ll see how you can call parent class constructors. If you are aware of the concept of inheritance, you would know that a class can extend another class to build on its functionalities.
Now, there’s a possibility that both child and parent classes have their own constructors. So how would you call the constructor of the parent class when a child class object is being instantiated?
Let’s try to understand it with an example.
<?php class Person { private $name; public function __construct($name) { $this->name=$name; } } class Employee extends Person { private $employee_id; public function __construct($name, $employee_id) { parent::__construct($name); $this->employee_id=$employee_id; } } $obj=new Employee('John', 'J123'); ?>
As you can see, the Employee
class extends the Person
class. Now, when the Employee
object is instantiated, the __construct()
method of the Employee
class is called. In this method, we’ve used the special parent
keyword to call the __construct()
method of the parent class. And thus, it would end up calling the __construct()
method of the Person
class. It’s always a good practice to call the __construct()
method of the parent class if your class extends any class.
Conclusion
Today, we discussed constructors in PHP along with a couple of real-world examples. You saw how to create a constructor, and some use-cases for constructors in PHP classes.
Check out some of our other posts on object-oriented programming in PHP!
This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
Sajal Soni | Sciencx (2021-07-20T16:34:05+00:00) Understanding PHP Constructors. Retrieved from https://www.scien.cx/2021/07/20/understanding-php-constructors/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.