43: Handle Class Names Explicitly in Type Checks
Overview
Section titled “Overview”Check an instance and a class name with is_a() and is_subclass_of(). PHP 8.6 deprecates passing a class string when the allow-string flag is false.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable class-string-guards.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/43-class-string-guards/class-string-guards.php<?php
declare(strict_types=1);
class Handler{}
final class CsvHandler extends Handler{}
$handler = new CsvHandler();$name = CsvHandler::class;echo 'Instance: ', $handler instanceof Handler ? 'yes' : 'no', PHP_EOL;echo 'Class is a handler: ', is_a($name, Handler::class, true) ? 'yes' : 'no', PHP_EOL;echo 'Class extends handler: ', is_subclass_of($name, Handler::class, true) ? 'yes' : 'no', PHP_EOL;Expected Result
Section titled “Expected Result”Instance: yesClass is a handler: yesClass extends handler: yesWhy It Works
Section titled “Why It Works”Use instanceof or pass an object when checking a live instance. Pass true explicitly for trusted class names. The class-string path can invoke autoloading, so restrict class names before passing through values from users.
Exercise
Section titled “Exercise”Replace the class name with the base class and compare the results. is_a() accepts the base class itself while is_subclass_of() requires a stricter relationship.
Wrap-up
Section titled “Wrap-up”Continue with Set a Limit for php://filter Chains.