Skip to content
AgileLogics
5 min read

Object-Oriented Basics

Prerequisites: Including files

A class is a blueprint for objects. It groups related data (properties) and behavior (methods).

class User
{
    public string $name;
    public string $role;

    public function __construct(string $name, string $role = 'member')
    {
        $this->name = $name;
        $this->role = $role;
    }

    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }
}

$user = new User('Ada', 'admin');
echo $user->isAdmin(); // true (1)

Practice

Create a Product class with name and price properties and a method describe() returning "<name>: $<price>".

Show solution
class Product
{
    public function __construct(
        public string $name,
        public float $price,
    ) {}

    public function describe(): string
    {
        return "{$this->name}: \${$this->price}";
    }
}