Appearance
PHP Type Conventions
Introduction
IxDF's PHP type system usage favors explicit, strongly-typed code to enhance clarity, IDE support, and static analysis capabilities. This guide covers our conventions for using PHP's type system effectively.
Strict Types Declaration
Always use declare(strict_types=1); in all files. This catches type-related bugs early and promotes more thoughtful code, resulting in increased stability.
Type Declarations
Property Types
- Always specify property types when possible
- Use union types when necessary
- Consider nullable types carefully
php
class Example
{
private string $name;
private ?int $age;
private DateTime|string $date;
}Method Types
- Always specify parameter types when possible
- Always use return types when possible
- Use
voidfor methods that return nothing - Use
neverfor methods that always throw an exception
php
public function processUser(string $name, ?int $age): void
{
// Implementation
}
public function throwError(): never
{
throw new RuntimeException('Error occurred');
}Type Casting
Prefer type-casting over dedicated methods for better performance:
php
// GOOD
$score = (int) '7';
$hasMadeAnyProgress = (bool) $this->score;
// BAD
$score = intval('7');
$hasMadeAnyProgress = boolval($this->score);Traversable Types
Use advanced PHPDoc syntax to describe traversable types:
php
/** @return list<string> */
/** @return array<int, Type> */
/** @return Collection<TKey, TValue> */
/** @return array{foo: string, optional?: int} */Generic Types and Templates
Use Psalm template annotations for generic types:
php
/**
* @template T of \Illuminate\Notifications\Notification
* @param class-string<T> $notificationFQCN
* @return T
*/
protected function initialize(string $notificationFQCN): Notification
{
// Implementation...
}