Php

Classes and objects

What are Classes and Objects?

  • A class is like a blueprint for creating objects.

  • An object is an instance of a class — it has properties (data) and methods (functions).


Defining a Class

php
class Car {
// Properties (variables)
public $brand;
public $color;

// Method (function)
public function drive() {
echo "Driving the $this->color $this->brand car.";
}
}


Creating Objects

php
$myCar = new Car(); // Create object
$myCar->brand = "Toyota"; // Set property
$myCar->color = "Red"; // Set property

$myCar->drive(); // Output: Driving the Red Toyota car.


Constructor Method

Use a constructor to initialize properties when the object is created.

php
class Person {
public $name;
public $age;

public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

public function introduce() {
echo "Hi, I'm $this->name and I'm $this->age years old.";
}
}

$user = new Person("Alice", 30);
$user->introduce(); // Output: Hi, I'm Alice and I'm 30 years old.


Object-Oriented Concepts

Concept Description
Class Blueprint or template
Object Instance of a class
Property Variable inside a class
Method Function inside a class
Constructor Special method that runs when object is created
$this Refers to the current object

Visibility (Access Modifiers)

Modifier Meaning
public Accessible from anywhere
private Only accessible within the class
protected Accessible within class & subclasses
php
class BankAccount {
private $balance = 0;

public function deposit($amount) {
$this->balance += $amount;
}

public function getBalance() {
return $this->balance;
}
}

$acc = new BankAccount();
$acc->deposit(1000);
echo $acc->getBalance(); // Output: 1000


Summary

  • Use classes to organize related code.

  • Create objects from classes to work with that code.

  • Use properties for data and methods for behavior.

  • Encapsulation helps protect and manage data (using private/public).

Leave a Reply

Your email address will not be published. Required fields are marked *