Search⌘ K
AI Features

Introduction to OOP Class

Explore the fundamentals of object-oriented programming in PHP by learning how to create classes and define properties. Understand why OOP improves code organization, modularity, and efficiency compared to procedural programming. This lesson helps you grasp the structure and naming conventions for classes and properties, setting a foundation for building scalable PHP applications.

What is OOP?

Object-oriented programming (OOP) is a programming style in which it is customary to group all of the variables and functions of a particular topic into a single class.

Why is OOP more efficient than procedural language?

Object-oriented programming is considered to be more advanced and efficient than the procedural style of programming. This efficiency stems from the following facts:

  • It supports better code organization.
  • It provides modularity.
  • It reduces the need for repetition.

That being said, we may still prefer the procedural style in small and simple projects. However, as our projects grow in complexity, we’re better off using OOP.

What is a class?

In order to create a class, we group the code that handles a particular topic into one place. For example, we can group pieces of code that handle users into a “User” class, the code that handles posts into a “Post” class, and the code that is devoted to comments into a “Comment” class. Generally, we name classes using a singular noun that starts with a capital letter.

How to declare a class

For the example given below, we’re going to create a Car class in which we’ll write code related to cars:

PHP
<?php
class Car {
// The code
}
?>

In line 2, we declare the class with the class keyword and write its name by capitalizing the first letter.

Note: If the class name contains more than one word, we capitalize each word. This is known as the upper camel case. For example, JapaneseCars, AmericanIdol, EuropeTour, and so on.

In lines 2 and 4, we enclose the class body within curly braces.

How to add properties to a class

We call properties to the variables inside a class. Properties can accept values like strings, integers, and booleans (true/false values) like any other variable.

Let’s add some properties to the Car class.

PHP
<?php
class Car {
public $comp;
public $color = "beige";
public $hasSunRoof = true;
}
?>
  • In line 3, we put the public keyword in front of class property $comp.

  • The naming convention is to start the property name with a lowercase letter.

  • If the name contains more than one word, all of the words start with an uppercase letter except for the first word. For example, $color or $hasSunRoof.

  • A property can have a default value, like $color = 'beige' in line 4.

  • We can also create a property without a default value. See the property $comp in line 3.