Skip to content

08: Inspect Property Read and Write Access

Check whether a form hydrator can read or write a property from public scope. Visibility and the state of a readonly property both influence the answer.

  • 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 property-access-reflection.php example.

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

Terminal window
php code/php-8-6/08-property-access-reflection/property-access-reflection.php
property-access-reflection.php
<?php
declare(strict_types=1);
final class Article
{
public string $title = 'Feature tour';
public private(set) string $slug = 'feature-tour';
public readonly int $id;
public function assignId(int $id): void
{
$this->id = $id;
}
}
$article = new Article();
foreach (['title', 'slug', 'id'] as $name) {
$property = new ReflectionProperty(Article::class, $name);
printf("%s read=%s write=%s\n", $name,
$property->isReadable(null, $article) ? 'yes' : 'no',
$property->isWritable(null, $article) ? 'yes' : 'no');
}
$article->assignId(7);
$id = new ReflectionProperty(Article::class, 'id');
echo 'Initialized id readable: ', $id->isReadable(null, $article) ? 'yes' : 'no', PHP_EOL;
title read=yes write=yes
slug read=yes write=no
id read=no write=no
Initialized id readable: yes

Pass null for global scope and pass the actual object to include its initialization state. A class scope can yield a different result for private setters. By default the tests account for property hooks and magic access.

Check slug with Article::class as the scope and compare it with the result from public scope.

Continue with Default Values for Readonly Properties.