Constructor (__construct)
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 7 of 91.
The __construct method is a special method that automatically runs when you create a new object. It initializes the object's properties.
Here is an example of a class with a constructor:
<?php
class Dog {
public $name;
public $breed;
public function __construct($name, $breed) {
$this->name = $name;
$this->breed = $breed;
}
}The __construct method takes parameters and assigns them to properties using $this.
Create objects using the constructor:
$rex = new Dog("Rex", "German Shepherd");
$buddy = new Dog("Buddy", "Golden Retriever");When you call new Dog("Rex", "German Shepherd"), PHP automatically calls __construct and passes the arguments.
Access the properties that were set by the constructor:
echo $rex->name . "\n";
echo $rex->breed . "\n";
echo $buddy->name . "\n";
echo $buddy->breed . "\n";Output:
Rex
German Shepherd
Buddy
Golden RetrieverYou can also have a constructor with default parameter values:
class Cat {
public $name;
public $age;
public function __construct($name, $age = 1) {
$this->name = $name;
$this->age = $age;
}
}
$fluffy = new Cat("Fluffy", 3);
$whiskers = new Cat("Whiskers"); // age defaults to 1
echo $fluffy->name . " is " . $fluffy->age . " years old\n";
echo $whiskers->name . " is " . $whiskers->age . " years old\n";Output:
Fluffy is 3 years old
Whiskers is 1 years oldKey Point: The __construct method ensures every object is properly set up with its initial data when created. It saves you from manually setting properties after object creation.
Challenge
EasyYou are given PHP files (book.php and driver.php) to implement a book system.
Your task is to:
- Complete the
Bookclass inbook.phpwith a__constructmethod that initializes$title,$author, and$pagesproperties - In
driver.php, import and create a book object for"Harry Potter"by"J.K. Rowling"with400pages
Follow the TODO comments in each file.
Cheat sheet
The __construct method is a special method that automatically runs when you create a new object to initialize its properties.
Define a constructor in a class:
<?php
class Dog {
public $name;
public $breed;
public function __construct($name, $breed) {
$this->name = $name;
$this->breed = $breed;
}
}Create objects using the constructor:
$rex = new Dog("Rex", "German Shepherd");
$buddy = new Dog("Buddy", "Golden Retriever");Access properties set by the constructor:
echo $rex->name; // Rex
echo $rex->breed; // German ShepherdConstructors can have default parameter values:
class Cat {
public $name;
public $age;
public function __construct($name, $age = 1) {
$this->name = $name;
$this->age = $age;
}
}
$fluffy = new Cat("Fluffy", 3);
$whiskers = new Cat("Whiskers"); // age defaults to 1Try it yourself
<?php
require_once 'book.php';
// TODO: Create a Book object with:
// title: "Harry Potter", author: "J.K. Rowling", pages: 400
$myBook = ?;
echo "'" . $myBook->title . "' by " . $myBook->author . ", " . $myBook->pages . " pages\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern