search
HomeBackend DevelopmentPHP TutorialObject-Oriented PHP With Classes and Objects

In this article, we're going to explore the basics of object-oriented programming using PHP classes.

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.

What Is Object-Oriented Programming (OOP)?

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  (to create object in PHP), 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 nameage, 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.

Let's keep diving in to learn how to create objects in PHP.

What Is a PHP Class?

First we need to understand what PHP classes are. 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 <br>class Employee<br>{<br>  private $first_name;<br>  private $last_name;<br>  private $age;<br> <br>  public function __construct($first_name, $last_name, $age)<br>  {<br>    $this->first_name = $first_name;<br>    $this->last_name = $last_name;<br>    $this->age = $age;<br>  }<br><br>  public function getFirstName()<br>  {<br>    return $this->first_name;<br>  }<br><br>  public function getLastName()<br>  {<br>    return $this->last_name;<br>  }<br><br>  public function getAge()<br>  {<br>    return $this->age;<br>  }<br>}<br>?><br>

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.

Class Properties in PHP

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 propertiesfirst_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 in PHP. This is the safest access level for properties. We’ll discuss the different access levels for class properties and methods in PHP later in this article.

Constructors for PHP Classes

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.

Methods for PHP Classes

We can think of class methods in PHP 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.

What Is an Object in PHP?

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 <br>class Employee<br>{<br>  private $first_name;<br>  private $last_name;<br>  private $age;<br> <br>  public function __construct($first_name, $last_name, $age)<br>  {<br>    $this->first_name = $first_name;<br>    $this->last_name = $last_name;<br>    $this->age = $age;<br>  }<br><br>  public function getFirstName()<br>  {<br>    return $this->first_name;<br>  }<br><br>  public function getLastName()<br>  {<br>    return $this->last_name;<br>  }<br><br>  public function getAge()<br>  {<br>    return $this->age;<br>  }<br>}<br>?><br>

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 <br>$objEmployee = new Employee('Bob', 'Smith', 30);<br><br>echo $objEmployee->getFirstName(); // print 'Bob'<br>echo $objEmployee->getLastName(); // prints 'Smith'<br>echo $objEmployee->getAge(); // prints '30'<br>?><br>

The following image is a graphical representation of the Employee class and some of its instances.

Object-Oriented PHP With Classes and Objects

Simply put, a class is a blueprint which you can use to create structured objects.

Encapsulation

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 discussionaccess levels.

Access Levels

When you define a property or a method in a class, you can declare it to have one of these three access levelspublic, private, or protected.

Public Access

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 <br>class Employee<br>{<br>  private $first_name;<br>  private $last_name;<br>  private $age;<br> <br>  public function __construct($first_name, $last_name, $age)<br>  {<br>    $this->first_name = $first_name;<br>    $this->last_name = $last_name;<br>    $this->age = $age;<br>  }<br><br>  public function getFirstName()<br>  {<br>    return $this->first_name;<br>  }<br><br>  public function getLastName()<br>  {<br>    return $this->last_name;<br>  }<br><br>  public function getAge()<br>  {<br>    return $this->age;<br>  }<br>}<br>?><br>

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.

Private Access

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 <br>$objEmployee = new Employee('Bob', 'Smith', 30);<br><br>echo $objEmployee->getFirstName(); // print 'Bob'<br>echo $objEmployee->getLastName(); // prints 'Smith'<br>echo $objEmployee->getAge(); // prints '30'<br>?><br>

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.

Protected Access

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

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.

Object-Oriented PHP With Classes and Objects

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 <br>class Employee<br>{<br>  private $first_name;<br>  private $last_name;<br>  private $age;<br> <br>  public function __construct($first_name, $last_name, $age)<br>  {<br>    $this->first_name = $first_name;<br>    $this->last_name = $last_name;<br>    $this->age = $age;<br>  }<br><br>  public function getFirstName()<br>  {<br>    return $this->first_name;<br>  }<br><br>  public function getLastName()<br>  {<br>    return $this->last_name;<br>  }<br><br>  public function getAge()<br>  {<br>    return $this->age;<br>  }<br>}<br>?><br>

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

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 <br>class Employee<br>{<br>  private $first_name;<br>  private $last_name;<br>  private $age;<br> <br>  public function __construct($first_name, $last_name, $age)<br>  {<br>    $this->first_name = $first_name;<br>    $this->last_name = $last_name;<br>    $this->age = $age;<br>  }<br><br>  public function getFirstName()<br>  {<br>    return $this->first_name;<br>  }<br><br>  public function getLastName()<br>  {<br>    return $this->last_name;<br>  }<br><br>  public function getAge()<br>  {<br>    return $this->age;<br>  }<br>}<br>?><br>

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.

Note: 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.

Conclusion

Now you know the basics of object-oriented programming using PHP classes. 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.

The above is the detailed content of Object-Oriented PHP With Classes and Objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.