OOP Basics

Back

Loading concept...

🏭 PHP OOP Basics: Building Your Own LEGO Factory!

Imagine you have a magical LEGO factory. Instead of building one car at a time, you create a blueprint that can make unlimited cars—each with its own color, speed, and special features. That’s exactly what Object-Oriented Programming (OOP) does in PHP!


🎯 The Big Picture

Think of OOP like this:

Real World PHP OOP
Blueprint for a toy Class
The actual toy Object
Toy’s color, size Properties
What the toy can do Methods
“This toy” (pointing) $this
Building the toy Constructor
Breaking down the toy Destructor
Who can touch it Access Modifiers

📦 What is a Class?

A class is like a recipe or blueprint. It describes what something IS and what it CAN DO—but it’s not the real thing yet!

Think of it like a cookie cutter. The cutter isn’t a cookie, but it tells you exactly what shape your cookies will be.

class Dog {
    // This is our blueprint
    // for making dogs!
}

That’s it! You just made your first class. It’s empty for now, but it’s ready to become something amazing.


🐕 What is an Object?

An object is the real thing made from your blueprint.

If Dog is the cookie cutter, then each actual dog you create is a cookie!

class Dog {
    // Blueprint
}

// Let's make REAL dogs!
$buddy = new Dog();
$max = new Dog();
$bella = new Dog();

See that word new? It’s like saying “Build me one!” Each dog is a separate object—Buddy, Max, and Bella are all different dogs, even though they came from the same blueprint.


🎨 What are Properties?

Properties are like labels on a box that describe what’s inside.

A dog has a name, age, and color. These are its properties!

class Dog {
    public $name;
    public $age;
    public $color;
}

// Create a dog and set properties
$buddy = new Dog();
$buddy->name = "Buddy";
$buddy->age = 3;
$buddy->color = "Golden";

echo $buddy->name;  // Buddy

Notice the arrow -> ? It’s like pointing and saying “this dog’s name.”


🏃 What are Methods?

Methods are actions—things your object can DO!

A dog can bark, run, and eat. These are methods!

class Dog {
    public $name;

    public function bark() {
        echo "Woof! Woof!";
    }

    public function run() {
        echo "Running fast!";
    }
}

$buddy = new Dog();
$buddy->bark();  // Woof! Woof!
$buddy->run();   // Running fast!

Methods are like buttons on a toy. Push the button, the toy does something!


👆 The Magic $this Keyword

Here’s where it gets exciting! How does a dog know its OWN name?

$this is like pointing at yourself in a mirror. It means “ME, this object!”

class Dog {
    public $name;

    public function introduce() {
        echo "Hi! My name is "
             . $this->name;
    }
}

$buddy = new Dog();
$buddy->name = "Buddy";
$buddy->introduce();
// Hi! My name is Buddy

$max = new Dog();
$max->name = "Max";
$max->introduce();
// Hi! My name is Max

When Buddy calls introduce(), $this means Buddy. When Max calls introduce(), $this means Max.

It’s like each dog pointing at themselves!


🎁 The Constructor: Birthday Party!

What if we want to give our dog a name THE MOMENT it’s born? That’s what a constructor does!

A constructor runs automatically when you create an object. It’s like a welcome party!

class Dog {
    public $name;
    public $age;

    // The magic birthday party!
    public function __construct(
        $name,
        $age
    ) {
        $this->name = $name;
        $this->age = $age;
        echo "$name is born!";
    }
}

// Buddy is born with name & age
$buddy = new Dog("Buddy", 2);
// Output: Buddy is born!

echo $buddy->name;  // Buddy
echo $buddy->age;   // 2

The __construct method (with two underscores) is special. PHP calls it automatically whenever you use new.


💤 The Destructor: Goodbye Party!

Just like there’s a birthday party, there’s a goodbye party when an object is no longer needed.

class Dog {
    public $name;

    public function __construct($name) {
        $this->name = $name;
        echo "$name arrived!\n";
    }

    public function __destruct() {
        echo $this->name
             . " says goodbye!\n";
    }
}

$buddy = new Dog("Buddy");
// Buddy arrived!

// When script ends or
// object is unset...
// Buddy says goodbye!

Destructors are useful for cleanup—like closing files or database connections when you’re done.


🔐 Access Modifiers: The Security Guards

Not everyone should touch everything! Access modifiers are like security levels.

The Three Security Levels

graph TD A["Access Modifiers"] --> B["public 🌍"] A --> C["private 🔒"] A --> D["protected 🛡️"] B --> E["Everyone can access"] C --> F["Only the class itself"] D --> G["Class + its children"]

🌍 Public: Open to Everyone!

class Dog {
    public $name = "Buddy";
}

$dog = new Dog();
echo $dog->name;  // Works!
$dog->name = "Max";  // Works!

🔒 Private: Secret! Only I Know!

class Dog {
    private $secret = "I love cats";

    public function tellSecret() {
        // I can see my own secret
        return $this->secret;
    }
}

$dog = new Dog();
// echo $dog->secret;  // ERROR!
echo $dog->tellSecret();
// I love cats

Private means only the class itself can see or change it. Not even objects can access it directly!

🛡️ Protected: Family Only!

class Animal {
    protected $type = "mammal";
}

class Dog extends Animal {
    public function getType() {
        // Child can access parent's
        // protected property
        return $this->type;
    }
}

$dog = new Dog();
// echo $dog->type;  // ERROR!
echo $dog->getType();  // mammal

Protected is for family secrets—the class and its children can see it, but outsiders cannot.


🎯 Putting It All Together

Let’s build a complete example using everything we learned!

class Pet {
    // Properties
    private $name;
    private $energy = 100;
    public $species;

    // Constructor
    public function __construct(
        $name,
        $species
    ) {
        $this->name = $name;
        $this->species = $species;
        echo "Welcome, $name!\n";
    }

    // Methods
    public function play() {
        if ($this->energy >= 20) {
            $this->energy -= 20;
            echo $this->name
                 . " is playing!\n";
        } else {
            echo $this->name
                 . " is too tired.\n";
        }
    }

    public function rest() {
        $this->energy = 100;
        echo $this->name
             . " feels refreshed!\n";
    }

    public function getEnergy() {
        return $this->energy;
    }

    // Destructor
    public function __destruct() {
        echo "Bye, "
             . $this->name . "!\n";
    }
}

// Create pets
$cat = new Pet("Whiskers", "Cat");
// Welcome, Whiskers!

$cat->play();  // Whiskers is playing!
$cat->play();  // Whiskers is playing!
$cat->play();  // Whiskers is playing!
$cat->play();  // Whiskers is playing!
$cat->play();  // Whiskers is too tired.

$cat->rest();  // Whiskers feels refreshed!
// End of script: Bye, Whiskers!

🌟 Quick Reference

Concept What It Does Example
Class Blueprint class Dog {}
Object Real thing new Dog()
Property Data/values $this->name
Method Actions function bark()
$this “This object” $this->name
Constructor Auto-runs on birth __construct()
Destructor Auto-runs on death __destruct()
public Anyone can access public $name
private Only class can access private $secret
protected Class + children protected $type

🎉 You Did It!

You just learned the foundation of Object-Oriented Programming in PHP!

Think about it like this:

  • Classes are your LEGO instruction manuals
  • Objects are the actual LEGO builds
  • Properties are the colors and sizes of pieces
  • Methods are what your LEGO creation can do
  • $this is your creation pointing at itself
  • Constructor is the moment you start building
  • Destructor is when you take it apart
  • Access Modifiers decide who can touch what

Now go build something amazing! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.