How to create a class in PHP?

Summary:

PHP classes are a subset of objects. They can an entire object model. They have properties and functions. They are a core feature of object-oriented programming in PHP. Check out the article to read more.

Class in PHP

This article focuses on how to create a class in PHP. A class is a fundamental concept in object oriented programming so the article features a section about PHP OOP basics. If you’re already familiar with OOP concepts you can jump straight to the example following the OOP basics section.

However, we recommend staying tuned from beginning to end to gain some really good insights about PHP OOP and especially about the concept of a class in PHP. 

Class and Object – PHP OOP Basics

A class is a fundamental concept in object-oriented programming. It is a blueprint or a template that defines an entity. The cool thing about a class is that you can create objects based on it. Let’s understand this class and object concept with an analogy.

class in php

Properties 

A master plan (class) forms a baseline for producing various cars in the image above. These cars have a color property that differs. A class defines properties, and objects assign values to these properties during construction.

Behaviors

But properties are one aspect of a class. A class also defines behaviour which in this analogy will be functions and behaviours relevant to cars, for instance, accelerating, decelerating, or breaking. 

All the objects of the same class exhibit similar behaviour. So, all these cars may look different, but they all exhibit the same behaviours or functions.

How to create a class in PHP?

As we have learned about classes and objects, let’s understand how they occur in code. Here’s a complete version of the Car class. Don’t worry about all the new keywords, as we will be building this class from the ground up in the following sections.

<?php
 
class Car
{
    public $color;
    private $chassis;
    public static $make = "Serpent";
 
    function __construct($color, $chassis)
    {
        $this->color = $color;
        $this->set_chasis($chassis);
    }
 
    function get_chasis()
    {
        return $this->chassis;
    }
 
    function set_chasis($chassis)
    {
        $this->chassis = $chassis;
    }
 
    function accelerate()
    {
        echo 'Accelerating';
    }
 
    function decelerate()
    {
        echo 'Decelerating';
    }
 
    static function welcome()
    {
        echo 'Welcome from '.self::$make;
    }
}
?>

Seems horribly difficult! Let’s not worry and learn it from the ground up.

Class in PHP

Defining a class is easy. Just type the keyword class followed by the class name, for instance – Car. By conventions, a class name should be capitalized. Moreover, keywords are case-sensitive so try not to type Class instead of class.

<?php
 
class Car
{
    //All the code goes in here. 
}
 
?>

Voila! We have the class in place. Let’s start defining properties next.

Properties of a Class in PHP

Let’s define a few properties of the Car class.

<?php
 
class Car
{
    public $color;
    private $chassis;
    public static $make = "Serpent";
}
?>

So, we have three properties in there – color, chassis and make

Note that the make has already been set to “Serpent”. There are some new keywords right there so let’s quickly see them.

Static vs Non Static 

The keyword static defines a class level property or a method. So the static members bind directly to class and you don’t need an object to access or modify them. For instance, the Car class here defines a make “Serpent”.

non-static members of a class in PHP

Now all the objects – cars are still “Serpent” regardless of the difference in their color or chassis. Contrary to static, the non-static members are bound to the object only, for instance, the color property is set when the car object is built and thus every car has different color.

Access Modifiers

You would be wondering about the keywords like public and private. These are access modifiers. Let’s see what are access modifiers.

Access modifiers controls the visibility of a property or a method. Sometimes you want to keep information strictly private and other times publicly available. Access modifiers thus controls the access to properties and methods.

The three access modifiers are:

  • public – The property or method can be accessed from anywhere. (Default)
  • protected – The property or method can be accessed withn the class and its subclasses.
  • private – The property or method can be accessed within the class only.

Private is the most strict modifier and thus doesn’t allow accessing or modifying the properties or methods directly. The class thus provide getter and setter functions to access and initiate the private members.

Constructor of a Class in PHP

The constructor function is invoked as we instantiate or in other words create objects. The constructor function initiates the properties of objects right at the time of constructing them. Let’s add a constructor function.

<?php
 
class Car
{
    public $color;
    private $chassis;
    public static $make = "Serpent";
 
    function __construct($color, $chassis)
    {
        $this->color = $color;
        $this->set_chasis($chassis);
    }
}
?>

The constructor function helps assign values to color and chassis, through the setter function.

Getter and Setter functions

As we have already discussed that private properties are not accessible outside the class. However, the getter and setter function allows us to access or set these properties indirectly. Well, this is data encapsulation which is yet another famous concept in OOP.

Let’s add getters and setters to the class.

<?php
 
class Car
{
    public $color;
    private $chassis;
    public static $make = "Serpent";
 
    function __construct($color, $chassis)
    {
        $this->color = $color;
        $this->set_chasis($chassis);
    }
    function get_chasis()
    {
        return $this->chassis;
    }
 
    function set_chasis($chassis)
    {
        $this->chassis = $chassis;
    }
 
}
?>

We will interact with the chassis through these methods rather than trying to access them directly.

Non-static methods

Non-static methods are bound to the objects of a class. They are only invoked on an object and couldn’t be invoked by a class directly. Let’s add some non-static methods.

<?php
 
class Car
{
    public $color;
    private $chassis;
    public static $make = "Serpent";
 
    function __construct($color, $chassis)
    {
        $this->color = $color;
        $this->set_chasis($chassis);
    }
    function get_chasis()
    {
        return $this->chassis;
    }
 
    function set_chasis($chassis)
    {
        $this->chassis = $chassis;
    }
     function accelerate()
    {
        echo 'Accelerating';
    }
 
    function decelerate()
    {
        echo 'Decelerating';
    }
}
?>

Perfect! All the car objects would be able to accelerate and decelerate.

Static methods

Static members are class level properties and methods. You don’t need to instantiate objects for accessing them. Let’s add a generic welcome function to the class.

<?php
 
class Car
{
    public $color;
    private $chassis;
    public static $make = "Serpent";
 
    function __construct($color, $chassis)
    {
        $this->color = $color;
        $this->set_chasis($chassis);
    }
    function get_chasis()
    {
        return $this->chassis;
    }
 
    function set_chasis($chassis)
    {
        $this->chassis = $chassis;
    }
     function accelerate()
    {
        echo 'Accelerating';
    }
 
    function decelerate()
    {
        echo 'Decelerating';
    }
     static function welcome()
    {
        echo 'Welcome from '.self::$make;
    }
 
}
?>

Voila! The class is now completely built. Let’s instantiate a few objects of the Car.

Objects of a class in PHP

The following code instantiates two objects of the class Car and invokes the accelerate method. Also, note that the color property is public and could be accessed directly while the private property chassis is accessed through a getter method.

Car::welcome(); //Static method.
 
$car1 = new Car('Red', '111-010-220');
$car2 = new Car('Green', '007-010-210');
 
echo $car1->color.' car is '.$car1->accelerate();
echo $car2->color.' car is '.$car2->accelerate();
 
/*
Welcome from Serpent
Red car with chassis 111-010-220 is Accelerating
Green car with chassis 007-010-210 is Accelerating
*/

We have the cars running now so let’s race to the conclusion now.

Conclusion

That’s all for this article. We have covered alot of ground here starting from PHP OOP basics to writing a Car class and instantiating its objects. The article includes explanations of some important concepts like static and non-static as well as access modifiers. 

These are pretty much the basics. If you want to learn more about PHP OOP and PHP in general, stay tuned at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems