Functions & Arrays · 9 min read · Beginner
Typed Functions & PHP 8 Classes
Write self-documenting PHP 8 functions with parameter/return types and concise classes using constructor property promotion.
What you'll learn
- Annotate parameter types and return types (int, string, float, array)
- Define clean PHP 8 classes using constructor property promotion
- Call methods cleanly using the -> object operator
Modern PHP 8 eliminates boilerplate with constructor property promotion: declare visibility (public, private, readonly) directly inside __construct(...)!
class Course {
public function __construct(
public readonly string $title,
public readonly int $lessons,
) {}
}
Fill-in-the-Blank Exercise
Typed Function & Constructor Promotion
Declare a typed function returning int and use -> to call a method on $course.
function doubleValue(int $n): {
return $n * 2;
}
echo $coursesummary();Try It Yourself
PHPPHP 8 Class with Constructor Promotion
PHP 8 Output (WebAssembly)
Click Run PHP to execute real PHP 8 right in your browser.
Check Your Understanding
Score: 0 / 1
1. Which operator accesses a property or method on a PHP object instance?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.