Classes and Objects

Define a class with properties and methods, then create objects from it.

Syntaxclass Name { public $property; public function method() { ... } }

A class bundles properties (variables) and methods (functions) together.

Create an object with the new keyword. Inside a method, the special variable $this refers to the current object. Access members with the -> arrow.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Define a BankAccount class with a private balance property and deposit/withdraw methods to enforce invariants.
  • Create a Product class with public name and price properties used across a catalogue controller and view.
  • Instantiate a Logger class to pass as a dependency wherever structured log output is needed.

More examples

Class with properties and methods

Properties store object state; methods operate on that state via $this, the object's self-reference.

Example · php
<?php
class Rectangle {
    public float $width;
    public float $height;

    public function area(): float {
        return $this->width * $this->height;
    }
    public function perimeter(): float {
        return 2 * ($this->width + $this->height);
    }
}

$rect         = new Rectangle();
$rect->width  = 5.0;
$rect->height = 3.0;
echo $rect->area();      // 15
echo $rect->perimeter(); // 16

Checking object type with instanceof

instanceof checks whether a variable holds an object of a specific class, enabling safe type-based branching.

Example · php
<?php
class Dog {}
class Cat {}

$pet = new Dog();

if ($pet instanceof Dog) {
    echo 'Woof!';
}

Cloning objects

clone creates a shallow copy; modifying the clone's array property does not affect the original object.

Example · php
<?php
class Config {
    public array $settings = ['debug' => false];
}

$base = new Config();
$dev  = clone $base;
$dev->settings['debug'] = true;

var_dump($base->settings['debug']); // false
var_dump($dev->settings['debug']);  // true

Discussion

  • Be the first to comment on this lesson.