A class is a blueprint/template that defines the properties and methods common to all objects created from it. An object is an instantiated instance of a class stored in memory.
class Car // Class Name
{
// 1. Property (State)
public string $brand;
// 2. Method (Behavior)
public function startEngine(): string
{
return "Engine started!";
}
}
// 3. Object Instantiation
$myCar = new Car();
flowchart TD
A["Class Blueprint (Car)"] -->|new Car()| B["Instance Object 1 ($tesla)"]
A -->|new Car()| C["Instance Object 2 ($bmw)"]
B --> B1["$tesla->brand = 'Tesla'"]
C --> C1["$bmw->brand = 'BMW'"]
<?php
declare(strict_types=1);
class Product
{
// Typed Properties
public string $name;
public float $price;
public int $stockQuantity = 0;
// Method utilizing internal properties via $this
public function getFormattedPrice(): string
{
return "$" . number_format($this->price, 2);
}
public function isInStock(): bool
{
return $this->stockQuantity > 0;
}
}
// Instantiating multiple independent objects
$laptop = new Product();
$laptop->name = "Developer Laptop";
$laptop->price = 1499.99;
$laptop->stockQuantity = 5;
$mouse = new Product();
$mouse->name = "Wireless Mouse";
$mouse->price = 29.99;
$mouse->stockQuantity = 0;
echo "Item 1: {$laptop->name} | Price: {$laptop->getFormattedPrice()} | In Stock?: " . ($laptop->isInStock() ? "Yes" : "No") . "
";
echo "Item 2: {$mouse->name} | Price: {$mouse->getFormattedPrice()} | In Stock?: " . ($mouse->isInStock() ? "Yes" : "No") . "
";
ProductService, UserAccount).$this-> to Access Instance Members: Always reference instance properties and methods using $this->propertyName inside class methods.public string $name;) to prevent type assignment errors.Write a class Book with properties string $title and float $price, and instantiate an object $myBook = new Book();!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.