Codectionary / Developer documentation / PHP

Check Object Contracts with instanceof

Recognise classes, parent types and implemented interfaces before using their object APIs.

What it is and why to use it

An application boundary may receive values whose exact type is not yet known. instanceof checks whether a value is an object compatible with a class or interface. It also recognises inheritance, so a child object matches its parent type. This can support a guarded call to an object’s API when a typed parameter is not available at the boundary.

How it works

Write the value on the left and a class or interface name on the right. The result is a boolean. Scalars and null do not match an object type. An interface test asks whether an object satisfies that declared contract, not whether it happens to have a similarly named method. Prefer a typed parameter when every valid caller must already provide the contract.

Common mistakes and limitations

Do not use instanceof to validate decoded JSON fields or to establish that an object came from a trustworthy source. A class identity check says nothing about authorisation or internal data validity. Long chains of concrete-class checks often indicate behaviour that belongs in an interface or in the objects themselves.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

if ($value instanceof Renderable) { /* use its declared API */ }

Examples

Recognise a concrete type and its contracts

Check one object against its class, parent and interface.

<?php
declare(strict_types=1);

interface Renderable {
    public function render(): string;
}
class Component {}
class Badge extends Component implements Renderable {
    public function render(): string {
        return 'PHP';
    }
}
$badge = new Badge();
echo $badge instanceof Badge ? 'Badge' : 'Other', PHP_EOL;
echo $badge instanceof Component ? 'Component' : 'Other', PHP_EOL;
echo $badge instanceof Renderable ? $badge->render() : 'Not renderable', PHP_EOL;
  1. Badge is both its exact class and a subclass of Component.
  2. It explicitly implements Renderable and supplies its required string-returning method.
  3. All three checks succeed. Code that needs rendering can depend on the interface rather than the concrete Badge class.
  4. Expected output: Badge Component PHP

Guard an uncertain value

Avoid calling a date method on a non-date value.

<?php
declare(strict_types=1);

$value = null;
if ($value instanceof DateTimeInterface) {
    echo $value->format('Y-m-d'), PHP_EOL;
} else {
    echo 'No date supplied', PHP_EOL;
}
  1. null is not an object implementing DateTimeInterface, so the test is false.
  2. The branch that calls format is not executed.
  3. This handles an optional boundary value. A function that always requires a date should declare a DateTimeInterface parameter instead.
  4. Expected output: No date supplied

Best practices

  • Prefer interface checks over unnecessary concrete-class coupling.
  • Use typed parameters for required contracts and guards for uncertain boundaries.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading