Advanced PHP: Object-Oriented Programming


#1

What is Object-Oriented Programming?

Object-Oriented programming (OOP) is a special way of programming, which is very powerful and easy to manage. It helps us to prevent repetitions occurs when using procedural programming. OOP is famous because of its advantages like:

  • Ease of management
  • Ease of usage
  • Less repetition
  • Fast and efficient

Why should I learn PHP OOP?

If you are dreaming to be a good developer, understand object-oriented programming is essential. Yes, it’s hard to understand it. If you try and follow the correct steps, you will learn it step by step/

What will learn today?

In this tutorial, I’ll give you the basic idea of object-oriented programming. You can continue learning more about OOP here at my website.

There are 4 basic concepts in OOP.

  1. Classes
  2. Objects
  3. Properties
  4. Methods

If you understand this correctly, you win :tada:

A class wraps a code that handles a specific task or topic. It contains properties and methods.

class User {
    public $name;
    public $age;
    public setName($name) {
        $this -> name = $name;
    }
    public setAge($age) {
        $this -> age = $age;
    }
}

Here $name and $age are properties while setName() and setAge() are methods.

Creating a class does nothing. It’s a blueprint which tells that this should in this way. To make it happen, we will need to create objects from it. Multiple objects can be created from a class.

$john = new User();
$john -> setName('John');
$john -> setAge(42);

$lisa = new User();
$lisa -> setName('Lisa');
$lisa -> setAge(32);

echo $john -> age; // 42
echo $lisa -> age; // 32

new User() will create an object from the class. Then, the object can be saved in variables ($john and $lisa). We can call methods on an object ($john -> setName()). Also, we can access the properties of an object ($lisa -> age)

This is the basic of OOP in PHP.

Good luck!