Skip to content

43: Handle Class Names Explicitly in Type Checks

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.

  • 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.

A runnable class-string-guards.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/43-class-string-guards/class-string-guards.php
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;
Instance: yes
Class is a handler: yes
Class extends handler: yes

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.

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.

Continue with Set a Limit for php://filter Chains.