Classes and Objects
What is a Class?
Section titled “What is a Class?”A class is a blueprint for creating objects. It defines properties (data) and methods (operations) that objects of that type will have.
class Product { // Properties and methods go here}Class Members
Section titled “Class Members”Properties
Section titled “Properties”Properties store data for each object. Use visibility keywords to control access:
class Product { public $name; // Accessible from anywhere private $cost; // Only accessible within this class protected $category; // Accessible within this class and child classes}Methods
Section titled “Methods”Methods are functions that belong to a class:
class Product { public $name; public $price;
public function getDiscountedPrice($percent) { return $this->price * (1 - $percent / 100); }}The -> Operator
Section titled “The -> Operator”The arrow operator -> accesses an object’s properties and methods:
$product->name; // Access property$product->getPrice(); // Call methodThe $this Keyword
Section titled “The $this Keyword”Inside a class, $this refers to the current object. Use $this-> to access its own properties and methods:
class Product { public $name;
public function setName($name) { $this->name = $name; // $this->name is the property }}Creating Objects
Section titled “Creating Objects”Use the new keyword to create an object (instance) from a class:
$product = new Product();$product->name = "Laptop";$product->price = 999.99;
echo $product->name; // "Laptop"echo $product->getDiscountedPrice(10); // 899.99Constructor
Section titled “Constructor”The __construct() method runs automatically when creating an object:
class Product { public $name; public $price;
public function __construct($name, $price) { $this->name = $name; $this->price = $price; }}
$product = new Product("Laptop", 999.99);echo $product->name; // "Laptop"Constructor Property Promotion (PHP 8+)
Section titled “Constructor Property Promotion (PHP 8+)”A shorter syntax that declares and assigns properties in one step:
class Product { public function __construct( public string $name, public float $price ) {}}
$product = new Product("Laptop", 999.99);Static Members
Section titled “Static Members”Static properties and methods belong to the class itself, not to individual objects. Access them using :: instead of ->.
Static Properties
Section titled “Static Properties”class Product { public static int $count = 0;
public function __construct() { self::$count++; }}
new Product();new Product();echo Product::$count; // 2Static Methods
Section titled “Static Methods”class Calculator { public static function add($a, $b) { return $a + $b; }}
echo Calculator::add(5, 3); // 8 (no object needed)Use self:: to access static members from within the class.
Inheritance
Section titled “Inheritance”A class can extend another class to inherit its properties and methods. Use extends:
class Animal { public string $name;
public function speak() { return "Some sound"; }}
class Dog extends Animal { public function speak() { return "Woof!"; }}
$dog = new Dog();$dog->name = "Buddy";echo $dog->speak(); // "Woof!"Calling Parent Methods
Section titled “Calling Parent Methods”Use parent:: to call the parent class method:
class Cat extends Animal { public function speak() { return parent::speak() . " Meow!"; }}
$cat = new Cat();echo $cat->speak(); // "Some sound Meow!"Interfaces
Section titled “Interfaces”An interface defines methods a class must implement. Use implements:
interface Payable { public function getAmount(): float;}
class Invoice implements Payable { public function getAmount(): float { return 100.00; }}A class can implement multiple interfaces: class Order implements Payable, Printable
Magic Methods
Section titled “Magic Methods”Magic methods are special methods that PHP calls automatically in certain situations. They start with __.
__toString()
Section titled “__toString()”Returns a string representation when an object is used as a string:
class Product { public function __construct(public string $name, public float $price) {}
public function __toString(): string { return "{$this->name} - \${$this->price}"; }}
$product = new Product("Laptop", 999.99);echo $product; // "Laptop - $999.99"__get() and __set()
Section titled “__get() and __set()”Called when accessing or setting undefined/inaccessible properties:
class User { private array $data = [];
public function __get($name) { return $this->data[$name] ?? null; }
public function __set($name, $value) { $this->data[$name] = $value; }}
$user = new User();$user->name = "John"; // Calls __set('name', 'John')echo $user->name; // Calls __get('name') → "John"Example
Section titled “Example”A simple User class:
class User { public string $name; public string $email; private string $password;
public function __construct($name, $email, $password) { $this->name = $name; $this->email = $email; $this->password = password_hash($password, PASSWORD_DEFAULT); }
public function checkPassword($password) { return password_verify($password, $this->password); }}
// Usage$user = new User("John", "john@example.com", "secret123");echo $user->name; // "John"echo $user->checkPassword("secret123"); // true// echo $user->password; // Error: private property