Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?php class Product { // Properties (typed since PHP 7.4) public string $name; public float $price; public int $stock; // Constructor public function __construct(string $name, float $price, int $stock = 0) { $this->name = $name; $this->price = $price; $this->stock = $stock; } // Method public function totalValue(): float { return $this->price * $this->stock; } public function isInStock(): bool { return $this->stock > 0; } public function describe(): string { return sprintf( '%s — $%.2f (%d in stock)', $this->name, $this->price, $this->stock ); } } // Instantiate $widget = new Product('Widget', 9.99, 50); $gadget = new Product('Gadget', 49.99); echo $widget->describe(); // Widget — $9.99 (50 in stock) echo $widget->totalValue(); // 499.5 echo $gadget->isInStock() ? 'In stock' : 'Out of stock'; // Out of stock // Multiple independent instances $a = new Product('Alpha', 1.00, 10); $b = new Product('Beta', 2.00, 5); echo $a->name; // Alpha echo $b->name; // Beta — separate objects
Result
Open