codegurukool.com · Free coding tutorials & online compiler

Home › PHP Tutorial › PHP classes, objects and constructors

PHP classes, objects and constructors

Model things with object-oriented code.

A class is a blueprint and an object is one instance made with new. The __construct method runs when the object is created. Use $this to reach the object's own properties.

Example code

<?php
class Car {
  public string $brand;
  public function __construct(string $brand) {
    $this->brand = $brand;
  }
  public function honk(): string {
    return $this->brand . " says beep";
  }
}
$c = new Car("Volvo");
echo $c->honk();
?>

Run this code in the online editor

← PHP exceptionsPHP inheritance →