
Wikis & learning
Represent a catalog entry with an object
A class can keep a short title and the behavior that presents it together. Create independent instances when two entries have different values.
A class can keep a short title and the behavior that presents it together. Create independent instances when two entries have different values.
How it works
Constructor property promotion is available in PHP 8. Define the property on the constructor parameter, then read it through the object.
PHP example
<?php
class CatalogEntry {
public function __construct(public string $name) {}
public function label(): string {
return '[' . $this->name . ']';
}
}
echo (new CatalogEntry('Calendar'))->label();Expected result
[Calendar]
Try a variation
Construct a second entry and print both labels. Changing one instance should leave the other one alone.
Discussion
Sign in to participate.



