Objects and Classes in PHP: A Beginner’s Guide | PHP Beginner to Advance

Object-oriented programming (OOP) is a popular programming paradigm that is widely used in modern programming languages, including PHP. In this blog post, we’ll be taking a look at the basics of OOP in PHP, including classes, objects, and inheritance.

Classes in PHP

A class in PHP is a template or blueprint for creating objects. It defines the properties and methods that an object of that class will have. Here’s an example of a simple class called “Person”:

class Person {
  public $name;
  public $age;

  public function sayHello() {
    echo "Hello, my name is " . $this->name;
  }
}

In this example, we’ve created a class called Person that has two properties, $name and $age, and one method, sayHello(). The properties and methods of a class are defined within the curly braces {}.

Objects in PHP

An object is an instance of a class. To create an object, we use the new keyword followed by the class name and parentheses. Here’s an example of how to create an object of the Person class:

$person = new Person();
$person->name = "John Doe";
$person->age = 30;
$person->sayHello();

In this example, we’ve created an object called $person of the Person class and set its properties, name and age. We’ve also called the sayHello() method of the class, which will output the string “Hello, my name is John Doe”.

Inheritance in PHP

Inheritance is a way for one class to inherit the properties and methods of another class. A class that inherits from another class is called a subclass or child class, and the class that is being inherited from is called the superclass or parent class. Here’s an example of how to create a subclass called “Student” that inherits from the “Person” class:

class Student extends Person {
  public $studentId;

  public function sayHello() {
    echo "Hello, my name is " . $this->name . " and my student ID is " . $this->studentId;
  }
}

$student = new Student();
$student->name = "Jane Smith";
$student->age = 25;
$student->studentId = 123456;
$student->sayHello();

In this example, we’ve created a subclass called Student that inherits from the Person class. The Student class has a new property, $studentId, and a new method, sayHello(). The sayHello() method of the Student class overrides the sayHello() method of the Person class. When we create an object of the Student class and call its sayHello() method, it will output the string “Hello, my name is Jane Smith and my student ID is 123456”.

In Conclusion

Object-oriented programming is a powerful programming paradigm that is widely used in PHP. Understanding the basics of classes, objects, and inheritance is an important part of becoming a proficient PHP developer. With the help of classes and objects, it is easier to structure, organize, and reuse the code for your projects.

Here are the parts of the series