7. PHP 7/8+ New Features
What are Named Arguments (introduced in PHP 8.0)?
JuniorAnswer: Named arguments allow you to pass values by parameter name instead of position, making the code more readable and allowing you to skip optional parameters.
htmlspecialchars($string, double_encode: false);
What are Union Types (introduced in PHP 8.0)?
JuniorAnswer: Union types allow you to specify multiple types for a parameter, property, or return value, instead of just one.
function sum(int|float $a, int|float $b): int|float {
return $a + $b;
}
What are Match Expressions (introduced in PHP 8.0)?
JuniorAnswer: A safer and more concise alternative to switch that uses strict comparison and returns a value.
$status = match($code) {
200, 201 => 'success',
default => 'unknown',
};
What is the #[Override] attribute (introduced in PHP 8.3)?
Junior
Answer: The #[Override] attribute ensures that a method with the same name exists in a parent class or interface. This helps catch errors during refactoring.
class Child extends ParentClass {
#[Override]
public function existingMethod() {}
}
What is the json_validate() function (introduced in PHP 8.3)?
Junior
Answer: Checks if a string is a valid JSON without decoding it, which uses less memory.
if (json_validate($jsonString)) {
// string is valid JSON
}
What is dynamic class constant fetch (introduced in PHP 8.3)?
JuniorAnswer: A simplified syntax to fetch class constants using a variable.
$name = 'STATUS_ACTIVE';
echo MyClass::{$name};
What are the null, false, and true standalone types (introduced in PHP 8.2)?
Junior
Answer: These can now be used as standalone types for return values, parameters, and properties.
public function alwaysFalse(): false { return false; }
What is the Nullsafe Operator (introduced in PHP 8.0)?
JuniorAnswer: The ?-> operator allows you to safely access properties or methods on a potentially null value without throwing an error.
$country = $session?->user?->getAddress()?->country;
What are the new array functions introduced in PHP 8.4?
JuniorAnswer: PHP 8.4 introduced four new functions for searching and validating array elements using a callback: array_find(), array_find_key(), array_any(), and array_all().
$firstEven = array_find([1, 2, 3, 4], fn($v) => $v % 2 === 0); // 2
$anyEven = array_any([1, 3, 5], fn($v) => $v % 2 === 0); // false
What are the array_first() and array_last() functions (introduced in PHP 8.5)?
Junior
Answer: PHP 8.5 added native functions to get the first and last elements of an array without moving the internal array pointer.
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$first = array_first($arr); // 1
$last = array_last($arr); // 3
What is the new class instantiation syntax in PHP 8.4?
JuniorAnswer: PHP 8.4 allows accessing properties and methods of a newly instantiated class without needing to wrap the new expression in parentheses.
// Before PHP 8.4
$name = (new User())->getName();
// PHP 8.4
$name = new User()->getName();
What are the main differences between PHP 5.x and PHP 7/8?
MiddleAnswer: The transition from PHP 5 to PHP 7/8 brought significant improvements in performance, security, and developer experience.
Key Improvements in PHP 7/8:
-
Performance: PHP 7 is up to twice as fast as PHP 5.6, and PHP 8 introduced JIT (Just-In-Time) compilation for further speed gains in certain workloads.
-
Scalar Type Declarations: PHP 7/8 supports strict typing for
int,float,bool, andstring. -
Return Type Declarations: You can now specify the return type of a function.
-
Null Coalescing Operator (
??): Provides a shorthand for checking if a value is set and not null. -
Spaceship Operator (
<=>): Used for combined comparisons (less than, equal to, or greater than). -
Anonymous Classes: Support for creating classes on the fly.
-
Improved Error Handling: Many fatal errors were converted to exceptions in PHP 7, and PHP 8 introduced the
Errorclass hierarchy. -
Match Expressions (PHP 8): A more powerful and strict version of
switch. -
Named Arguments (PHP 8): Allows passing arguments by name.
-
Enums (PHP 8.1): Support for enumerations.
-
Readonly Properties (PHP 8.1): Properties that cannot be modified after initialization.
-
First-class Callable Syntax (PHP 8.1): Simplified syntax for function references.
-
Readonly Classes (PHP 8.2): Entire classes can be marked as readonly.
-
DNF Types (PHP 8.2): Combine union and intersection types.
-
#[Override] Attribute (PHP 8.3): Ensure a method overrides a parent method.
-
Typed Class Constants (PHP 8.3): Add type hints to class constants.
-
json_validate() (PHP 8.3): Check if a string is valid JSON without decoding.
-
Property Hooks (PHP 8.4): Support for computed properties with
getandsethooks. -
Asymmetric Visibility (PHP 8.4): Different visibility for reading and writing properties.
-
New Array Functions (PHP 8.4):
array_find(),array_find_key(),array_any(), andarray_all(). -
Simplified Class Instantiation (PHP 8.4): Create class and call method/property without extra parentheses:
new User()->name. -
Pipe Operator (PHP 8.5): New operator (
|>) for chaining function calls. -
URI Extension (PHP 8.5): A new built-in extension for URI parsing and manipulation.
-
array_first() and array_last() (PHP 8.5): Get first and last elements of an array.
-
#[\NoDiscard] Attribute (PHP 8.5): Warn when return value of a function is not used.
-
PIE (PHP 8.5+): Official PHP Installer for Extensions replaces PECL.
What are Enums (introduced in PHP 8.1)?
MiddleAnswer: Enumerations allow you to define a set of named constants, providing type safety for fixed sets of values.
enum Status: string {
case Pending = 'pending';
case Active = 'active';
}
What are Readonly Properties (introduced in PHP 8.1)?
MiddleAnswer: Properties that cannot be modified after they are initialized.
class BlogData {
public readonly string $title;
public function __construct(string $title) {
$this->title = $title;
}
}
What is the First-class callable syntax (introduced in PHP 8.1)?
MiddleAnswer: A simplified syntax to get a reference to any function or method.
$fn = strlen(...);
echo $fn('hello'); // 5
What is the never return type (introduced in PHP 8.1)?
Middle
Answer: Indicates that a function will never return normally (it either throws an exception or calls exit()).
function redirect(string $url): never {
header("Location: $url");
exit;
}
What are Typed Class Constants (introduced in PHP 8.3)?
MiddleAnswer: Class constants can now have type declarations, similar to properties and parameters.
class User {
const string ROLE = 'admin';
}
What is Constructor Property Promotion (introduced in PHP 8.0)?
MiddleAnswer: A shorthand syntax to define and initialize class properties directly in the constructor.
class User {
public function __construct(public string $name, public int $age) {}
}
What are Property Hooks (introduced in PHP 8.4)?
MiddleAnswer: Property hooks allow defining custom logic for getting and setting class properties directly on the property declaration, reducing the need for explicit getter and setter methods.
class User {
public string $name {
get => strtoupper($this->name);
set => strtolower($value);
}
}
What is the Pipe Operator (introduced in PHP 8.5)?
MiddleAnswer: The pipe operator (|>) allows passing the result of an expression as the first argument to a function or method, making it easier to chain multiple transformations.
$result = " hello world "
|> trim(...)
|> strtoupper(...)
|> (fn($str) => str_replace('WORLD', 'PHP 8.5', $str));
// Result: "HELLO PHP 8.5"
What are Readonly Classes (introduced in PHP 8.2)?
SeniorAnswer: Marking a class as readonly makes all its properties readonly and prevents dynamic properties.
readonly class Post {
public function __construct(public string $title) {}
}
What are Disjunctive Normal Form (DNF) Types (introduced in PHP 8.2)?
SeniorAnswer: Allows combining union and intersection types. Intersection types must be grouped with parentheses.
public function process((A&B)|null $entity) { ... }
What are Intersection Types (introduced in PHP 8.1)?
SeniorAnswer: Allow declaring that a parameter or return value must implement multiple interfaces or classes simultaneously.
public function count(Countable&Iterator $it) { ... }
What are Fibers (introduced in PHP 8.1)?
SeniorAnswer: A way to create lightweight coroutines for non-blocking I/O and asynchronous tasks. They allow pausing and resuming execution within a single thread.
What is Asymmetric Visibility (introduced in PHP 8.4)?
SeniorAnswer: It allows setting different visibility levels for reading and writing a property. This is typically used to have a property that is publicly readable but can only be modified from within the class (private set).
class User {
public private(set) string $id;
}
What is the #[\NoDiscard] attribute (PHP 8.5)?
Senior
Answer: It's a new built-in attribute that indicates the return value of a function or method must be used. Static analysis tools and some IDEs will warn if the result of such a function is ignored.
#[\NoDiscard]
function calculateImportantValue(): int {
return 42;
}
calculateImportantValue(); // Static analysis warning: Return value ignored.
What is PIE and how it relates to PECL?
SeniorAnswer: PIE (PHP Installer for Extensions) is the modern, official tool for installing PHP extensions, designed to replace the legacy PECL (which is now deprecated). It's distributed as a PHAR (like Composer) and works similarly, using PHP Foundation's repository.
# Example usage
pie install redis