8 New Feature on PHP 8
New Features:
- Nullsafe Operator
- Named Arguments
- Union Types
- Constructor Property Promotion
- Trailing Comma in Parameters
- Match Expression
- Throw Expression
- New String Methods
Nullsafe Operator
Null Safe operator, is the shorthand of the check properties are null or not with safe way. If property is null without giving any error just output a null value.
Nullsafe Opreator: ?->
Lets make an example:
Class Posts {
public function getPost($id) {
if($id) {
return (object) ['description' => 'lorem ipsum ...'];
}
}
}
$posts = new Posts();
$descripton = $posts->getPost(0)?->description;
var_dump($descripton);
In the example, there is getPost method that getting posts. $description variable get posts and look with nullsafe operator ?-> is getPost null? if not get the description property.
Named Arguments
The great new feature is Named Arguments. With PHP 8 its possible to use argument names when send them to methods (functions). Lets make an example:
savePost($title,$description) {
return [
'title' => $title,
'description' => $description
];
}
with PHP 7 and older versions when call method first write title argument then description like:
savePost('This is title', 'This is description');
but with PHP8 its possible to use argument names like:
savePost(description: 'This is description'', title: 'This is title')
Advantages:
- Don't need to remind ordering
- Dont need to write all variables if there is lots of default argument values like:
savePost($title, $description, $is_active=false, $user_id = 0, $is_premium=false)
in this method if only need to put $is_premium i must write all arguments in PHP 7 and older versions like:
savePost('This is title', 'This is description', false, 0, true)
with PHP 8 only write three argument just like:
savePost(description: 'This is description'', title: 'This is title', is_premium: true)
Union Types
Possible to define more than one type now. For example one argument can be float and int at the same time or one argument can be float and int and string at the same time. With new feature also can define more than one return types for functions. Let's look examples:
Class Math {
public int|float|string $number;
// Number also can be string
public function setNumber(int|float|string $number) {
$this->number = $number;
}
}
$math = new Math();
$math->setNumber(5.0);
// Check the type
var_dump($math->number);
Next example is union return type:
function user_load(int $id): User|false {
// Get User or:
return false;
}
Constructor Property Promotion
With PHP 8 it's possible to set arguments automatically in constructor. Don't need to set one by one inside the constructor method. Let's look with examples:
In PHP 7 and older versions:
class Post {
public string $title;
public string $description;
public DateTime $created_at;
public function __construct($title, $description, $created_at)
{
$this->title= $title;
$this->description= $description;
$this->created_at= $created_at;
}
}
In PHP 8:
class Post {
public function __construct(
public string $title,
public string $description,
public DateTime $created_at)
{
}
}
Trailing Comma in Parameters
With PHP 8 its possible to write one more comma while defining arguments. For example:
saveData($title, $description, $extra,)
After $extra argument there is a comma.
Match Expression
Good alternative for Switch-Case, let's explain with an example
$user_number = 5;
$response = match ($user_number) {
0 => 'No user',
1 => 'Only one user',
default => $user_number . ' user is there',
};
echo $response;
// Response will be "5 user is there"
Throw Expression
It's possible to define throw expressions in short if conditional statements. For example:
$name = $_GET['name'] ?? throw new Exception('Name Not Exists');
New String Methods
With PHP 8 there is three new string methods: str_contains
, str_starts_with
, str_ends_with
$text = 'Hello, wellcome to my office';
# String içeriyor mu? Eski versiyonlarda strpos
$is_contain = str_contains($text, 'come');
# Return True
$str_start = str_starts_with($text, 'He');
# Return True
$str_end = str_ends_with($text, 'ffice');
# Return True