Typed properties (PHP 7.4) are checked on every write. Without a default a typed property is uninitialized, not null, and reading it throws. Defaults must be constant expressions; new there is refused ("New expressions are not supported in this context"), though constructor parameter defaults accept it since PHP 8.1.
<?php
declare(strict_types=1);
class Product {
public string $sku; // typed, no default: uninitialized
public int $stock = 0;
public ?string $isbn = null; // nullable needs an explicit null
}
$p = new Product();
try { echo $p->sku; } catch (Error $e) { echo get_class($e), ': ', $e->getMessage(), "\n"; }
try { $p->stock = '12'; } catch (TypeError $e) { echo 'TypeError: ', $e->getMessage(), "\n"; }
$p->stok = 5; // a typo creates a dynamic propertyOutput
Error: Typed property Product::$sku must not be accessed before initialization TypeError: Cannot assign string to property Product::$stock of type int PHP Deprecated: Creation of dynamic property Product::$stok is deprecated in /tmp/ch04-09/typed.php on line 11
strict_types refused to coerce '12'. The last line needs php -d error_reporting=E_ALL, since Ubuntu 225 's CLI hides deprecations. Dynamic properties are deprecated since PHP 8.2 because they turn typos into silent state (Subsection 4.11.12).