In this article, we're going to explore the basics of object-oriented programming in PHP. We'll start with an introduction to classes and objects, and we'll discuss a couple of advanced concepts like inheritance and polymorphism in the latter half of this article.
Object-oriented programming, commonly referred to as OOP, is an approach which helps you to develop complex applications in a way that's easily maintainable and scalable over the long term. In the world of OOP, real-world entities such as Person
, Car
, or Animal
are treated as objects. In object-oriented programming, you interact with your application by using objects. This contrasts with procedural programming, where you primarily interact with functions and global variables.
In OOP, there's a concept of "class", which is used to model or map a real-world entity to a template of data (properties) and functionality (methods). An "object" is an instance of a class, and you can create multiple instances of the same class. For example, there is a single Person
class, but many person objects can be instances of this class—dan
, zainab
, hector
, etc.
The class defines properties. For example, for the Person class, we might have name
, age
, and phoneNumber
. Then each person object will have its own values for those properties.
You can also define methods in the class that allow you to manipulate the values of object properties and perform operations on objects. As an example, you could define a save
method which saves the object information to a database.
A class is a template which represents a real-world entity, and it defines properties and methods of the entity. In this section, we’ll discuss the basic anatomy of a typical PHP class.
The best way to understand new concepts is with an example. So let's have a look at the Employee
class in the following snippet, which represents the employee entity.
<?php class Employee { private $first_name; private $last_name; private $age; public function __construct($first_name, $last_name, $age) { $this->first_name = $first_name; $this->last_name = $last_name; $this->age = $age; } public function getFirstName() { return $this->first_name; } public function getLastName() { return $this->last_name; } public function getAge() { return $this->age; } } ?>
The class Employee
statement in the first line defines the Employee
class. Then, we go on to declare the properties, the constructor, and the other class methods.
You could think of class properties as variables that are used to hold information about the object. In the above example, we’ve defined three properties—first_name
, last_name
, and age
. In most cases, class properties are accessed via instantiated objects.
These properties are private
, which means they can only be accessed from within the class. This is the safest access level for properties. We’ll discuss the different access levels for class properties and methods later in this article.
A constructor is a special class method which is called automatically when you instantiate an object. We’ll see how to instantiate objects in the next couple of sections, but for now you just have to know that a constructor is used to initialize object properties when the object is being created.
You can define a constructor by defining the __construct
method.
We can think of class methods as functions that perform specific actions associated with objects. In most cases, they are used to access and manipulate object properties and perform related operations.
In the above example, we’ve defined the getLastName
method, which returns the last name associated with the object.
So that’s a brief introduction to the class structure in PHP. In the next section, we’ll see how to instantiate objects of the Employee
class.
In the previous section, we discussed the basic structure of a class in PHP. Now, when you want to use a class, you need to instantiate it, and the end result is an object. So we could think of a class as a blueprint, and an object is an actual thing that you can work with.
In the context of the Employee
class which we've just created in the previous section, let's see how to instantiate an object of that class.
<?php $objEmployee = new Employee('Bob', 'Smith', 30); echo $objEmployee->getFirstName(); // print 'Bob' echo $objEmployee->getLastName(); // prints 'Smith' echo $objEmployee->getAge(); // prints '30' ?>
You need to use the new
keyword when you want to instantiate an object of any class along with its class name, and you'll get back a new object instance of that class.
If a class has defined the __construct
method and it requires arguments, you need to pass those arguments when you instantiate an object. In our case, the Employee
class constructor requires three arguments, and thus we've passed these when we created the $objEmployee
object. As we discussed earlier, the __construct
method is called automatically when the object is instantiated.
Next, we've called class methods on the $objEmployee
object to print the information which was initialized during object creation. Of course, you can create multiple objects of the same class, as shown in the following snippet.
<?php $objEmployeeOne = new Employee('Bob', 'Smith', 30); echo $objEmployeeOne->getFirstName(); // prints 'Bob' echo $objEmployeeOne->getLastName(); // prints 'Smith' echo $objEmployeeOne->getAge(); // prints '30' $objEmployeeTwo = new Employee('John', 'Smith', 34); echo $objEmployeeTwo->getFirstName(); // prints 'John' echo $objEmployeeTwo->getLastName(); // prints 'Smith' echo $objEmployeeTwo->getAge(); // prints '34' ?>
The following image is a graphical representation of the Employee class and some of its instances.
Simply put, a class is a blueprint which you can use to create structured objects.
In the previous section, we discussed how to instantiate objects of the Employee
class. It's interesting to note that the $objEmployee
object itself wraps together properties and methods of the class. In other words, it hides those details from the rest of the program. In the world of OOP, this is called data encapsulation.
Encapsulation is an important aspect of OOP that allows you to restrict access to certain properties or methods of the object. And that brings us to another topic for discussion: access levels.
When you define a property or a method in a class, you can declare it to have one of these three access levels—public
, private
, or protected
.
When you declare a property or a method as public, it can be accessed from anywhere outside the class. The value of a public property can be modified from anywhere in your code.
Let's look at an example to understand the public access level.
<?php class Person { public $name; public function getName() { return $this->name; } } $person = new Person(); $person->name = 'Bob Smith'; echo $person->getName(); // prints 'Bob Smith' ?>
As you can see in the above example, we've declared the name
property to be public. Hence, you can set it from anywhere outside the class, as we've done here.
When you declare a property or a method as private
, it can only be accessed from within the class. This means that you need to define getter and setter methods to get and set the value of that property.
Again, let's revise the previous example to understand the private access level.
<?php class Person { private $name; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } } $person = new Person(); $person->name = 'Bob Smith'; // Throws an error $person->setName('Bob Smith'); echo $person->getName(); // prints 'Bob Smith' ?>
If you try accessing a private property from outside the class, it'll throw the fatal error Cannot access private property Person::$name
. Thus, you need to set the value of the private property using the setter method, as we did using the setName
method.
There are good reasons why you might want to make a property private. For example, perhaps some action should be taken (updating a database, say, or re-rendering a template) if that property changes. In that case, you can define a setter method and handle any special logic when the property is changed.
Finally, when you declare a property or a method as protected
, it can be accessed by the same class that has defined it and classes that inherit the class in question. We'll discuss inheritance in the very next section, so we'll get back to the protected access level a bit later.
Inheritance is an important aspect of the object-oriented programming paradigm which allows you to inherit properties and methods of other classes by extending them. The class which is being inherited is called the parent class, and the class which inherits the other class is called the child class. When you instantiate an object of the child class, it inherits the properties and methods of the parent class as well.
Let's have a look at the following screenshot to understand the concept of inheritance.
In the above example, the Person
class is the parent class, and the Employee
class extends or inherits the Person class and so is called a child class.
Let's try to go through a real-world example to understand how it works.
<?php class Person { protected $name; protected $age; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } private function callToPrivateNameAndAge() { return "{$this->name} is {$this->age} years old."; } protected function callToProtectedNameAndAge() { return "{$this->name} is {$this->age} years old."; } } class Employee extends Person { private $designation; private $salary; public function getAge() { return $this->age; } public function setAge($age) { $this->age = $age; } public function getDesignation() { return $this->designation; } public function setDesignation($designation) { $this->designation = $designation; } public function getSalary() { return $this->salary; } public function setSalary($salary) { $this->salary = $salary; } public function getNameAndAge() { return $this->callToProtectedNameAndAge(); } } $employee = new Employee(); $employee->setName('Bob Smith'); $employee->setAge(30); $employee->setDesignation('Software Engineer'); $employee->setSalary('30K'); echo $employee->getName(); // prints 'Bob Smith' echo $employee->getAge(); // prints '30' echo $employee->getDesignation(); // prints 'Software Engineer' echo $employee->getSalary(); // prints '30K' echo $employee->getNameAndAge(); // prints 'Bob Smith is 30 years old.' echo $employee->callToPrivateNameAndAge(); // produces 'Fatal Error' ?>
The important thing to note here is that the Employee
class has used the extends
keyword to inherit the Person
class. Now, the Employee
class can access all properties and methods of the Person
class that are declared as public or protected. (It can't access members that are declared as private.)
In the above example, the $employee
object can access getName
and setName
methods that are defined in the Person
class since they are declared as public.
Next, we've accessed the callToProtectedNameAndAge
method using the getNameAndAge
method defined in the Employee
class, since it's declared as protected. Finally, the $employee
object can't access the callToPrivateNameAndAge
method of the Person
class since it's declared as private.
On the other hand, you can use the $employee
object to set the age
property of the Person
class, as we did in the setAge
method which is defined in the Employee
class, since the age
property is declared as protected.
So that was a brief introduction to inheritance. It helps you to reduce code duplication, and thus encourages code reusability.
Polymorphism is another important concept in the world of object-oriented programming which refers to the ability to process objects differently based on their data types.
For example, in the context of inheritance, if the child class wants to change the behavior of the parent class method, it can override that method. This is called method overriding. Let's quickly go through a real-world example to understand the concept of method overriding.
<?php class Message { public function formatMessage($message) { return printf("<i>%s</i>", $message); } } class BoldMessage extends Message { public function formatMessage($message) { return printf("<b>%s</b>", $message); } } $message = new Message(); $message->formatMessage('Hello World'); // prints '<i>Hello World</i>' $message = new BoldMessage(); $message->formatMessage('Hello World'); // prints '<b>Hello World</b>' ?>
As you can see, we've changed the behavior of the formatMessage
method by overriding it in the BoldMessage
class. The important thing is that a message is formatted differently based on the object type, whether it's an instance of the parent class or the child class.
(Some object-oriented languages also have a kind of method overloading that lets you define multiple class methods with the same name but a different number of arguments. This isn't directly supported in PHP, but there are a couple of workarounds to achieve similar functionality.)
Object-oriented programming is a vast subject, and we've only scratched the surface of its complexity. I do hope that this tutorial helped you get you started with the basics of OOP and that it motivates you to go on and learn more advanced OOP topics.
Object-oriented programming is an important aspect in application development, irrespective of the technology you're working with. Today, in the context of PHP, we discussed a couple of basic concepts of OOP, and we also took the opportunity to introduce a few real-world examples.
Feel free to post your queries using the feed below!
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…