Classes and objects
So far you have worked with functions and arrays. When a program grows, a problem appears: the data and the functions that handle it are scattered. Object-oriented programming (OOP) groups them. A class is a mold that describes what data something has (properties) and what it can do (methods); an object is a concrete instance created from that mold. Think of a class Product and objects such as "Coffee at 3.50" or "Tea at 2.00". Modern PHP has full and very comfortable OOP.
Properties, constructor and methods
A class is declared with class and its name in PascalCase. Inside you define properties and methods. The __construct method runs when the object is created with new; in PHP 8 you can declare properties directly in the constructor parameters ("promotion"), which saves a lot of repeated code. Inside a method, $this is the object itself, and its members are reached with the arrow ->. Always type properties and methods, just as with functions.
<?php
declare(strict_types=1);
class Product
{
public function __construct(
public readonly string $name,
private float $price,
private int $stock = 0,
) {
}
public function price(): float
{
return $this->price;
}
public function applyDiscount(float $percent): void
{
if ($percent < 0 || $percent > 100) {
throw new InvalidArgumentException('Percent must be between 0 and 100.');
}
$this->price = round($this->price * (1 - $percent / 100), 2);
}
public function addStock(int $units): void
{
$this->stock += $units;
}
public function describe(): string
{
return "{$this->name}: {$this->price} ({$this->stock} in stock)";
}
}
$coffee = new Product('Coffee', 3.50, 10);
$coffee->applyDiscount(10);
$coffee->addStock(5);
echo $coffee->describe(), "\n"; // Coffee: 3.15 (15 in stock)
echo $coffee->name, "\n"; // Coffee (public readonly: can be read)
// $coffee->name = 'Tea'; // Error: cannot modify readonly property
// $coffee->price = 1.0; // Error: private propertyVisibility and encapsulation
Visibility controls who can touch each member. public is accessible from anywhere; private, only from inside the class itself; protected, from the class and its children. Encapsulation means keeping data private and exposing methods that guarantee rules: in the example, the price can never receive an invalid discount, because the only way to change it is applyDiscount. A readonly property is assigned only once, in the constructor, and never changes afterwards, ideal for objects that represent values.
Inheritance and static members
A class can extend another with extends and inherit its properties and methods, redefining those it needs; parent:: calls the parent's version. Use it only when there is a clear "is a" relation (a Book is a Product). A static member belongs to the class and not to the object: it is accessed with :: and is useful for counters or alternative constructors. A good modern rule: prefer composition (an object that contains others) to deep inheritance, which makes code rigid and hard to follow.
<?php
declare(strict_types=1);
class Book
{
private static int $count = 0;
public function __construct(protected string $title)
{
self::$count++;
}
public static function count(): int
{
return self::$count;
}
public function label(): string
{
return "Book: {$this->title}";
}
}
class Ebook extends Book
{
public function __construct(string $title, private float $sizeMb)
{
parent::__construct($title);
}
public function label(): string
{
return parent::label() . " ({$this->sizeMb} MB)";
}
}
$a = new Book('PHP Basics');
$b = new Ebook('Modern PHP', 2.4);
echo $a->label(), "\n"; // Book: PHP Basics
echo $b->label(), "\n"; // Book: Modern PHP (2.4 MB)
echo Book::count(), "\n"; // 2Remember too that objects are passed by object handle: if you pass an object to a function and it changes its properties, the original changes. If you need an independent copy, use clone. That is why value objects are usually immutable (readonly): instead of modifying them, you create a new one.
اختبر ما تعلمته
السؤال 1 من 1What does private do on a property?
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف