Skip to content

Commit a011ced

Browse files
authored
PHP 8.4: Discover the Latest and Greatest (#157)
1 parent 61c5990 commit a011ced

File tree

2 files changed

+235
-0
lines changed

2 files changed

+235
-0
lines changed
384 KB
Loading

src/assets/php8.4/php8.4.md

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
---
2+
title: PHP 8.4 - Discover the Latest and Greatest
3+
authorName: Isha Baral
4+
authorAvatar: https://avatars.githubusercontent.com/u/40142570?s=400&u=58ce006ccc626577e503b75788b2e8634a9b7d9c&v=4
5+
authorLink: https://github.com/ishabaral/
6+
createdAt: Sep 10, 2024
7+
tags: php, php8.4, latest
8+
banner: https://blog.jankaritech.com/src/assets/php8.4/images/php8.4.jpg
9+
---
10+
11+
Scheduled for release on November 21, 2024, PHP 8.4 packs some exciting new features and improvements. In this blog post, we'll explore some of the most interesting additions and changes:
12+
13+
1. New array helper functions
14+
2. Property hooks
15+
3. 'new' without parentheses
16+
4. Implicitly nullable parameter declarations deprecated
17+
5. New multibyte functions
18+
19+
## 1. New array helper functions
20+
21+
The following variants of array helper functions will be added in PHP 8.4:
22+
23+
* `array_find()`
24+
* `array_find_key()`
25+
* `array_any()`
26+
* `array_all()`
27+
28+
These functions will take an array and a callback function and return the following:
29+
30+
31+
| functions | Return value |
32+
| :---- | :---- |
33+
| `array_find()` | Returns the first element that meets the callback condition; `NULL` otherwise. |
34+
| `array_find_key()` | Returns the key of the first element that meets the callback condition; `NULL` otherwise. |
35+
| `array_any()` | Returns `true` if at least one element matches the callback condition; `false` otherwise. |
36+
| `array_all()` | Returns `true` if all elements match the callback condition; `false` otherwise. |
37+
38+
Note: `array_find()` retrieves only the first matching element. For multiple matches, consider using `array_filter()`.
39+
40+
### Example
41+
42+
Given an array with key-value pairs and a callback function:
43+
44+
```
45+
$array = ['1'=> 'red', '2'=> 'purple', '3' => 'green']
46+
47+
function hasLongName($value) {
48+
return strlen($value) > 4;
49+
}
50+
```
51+
52+
Here's how we can use the new functions:
53+
54+
1. `array_find()`:
55+
56+
```
57+
// Find the first color with a name length greater than 4
58+
59+
$result1 = array_find($array, 'hasLongName');
60+
61+
var_dump($result1); // string(5) "purple"
62+
```
63+
64+
2. `array_find_key()`:
65+
66+
```
67+
// Find the key of the first color with a name length greater than 4
68+
69+
$result2 = array_find_key($array, 'hasLongName');
70+
71+
var_dump($result2); // string(1) "2"
72+
```
73+
74+
3. `array_any()`:
75+
76+
```
77+
// Check if any color name has a length greater than 4
78+
79+
$result3 = array_any($array, 'hasLongName');
80+
81+
var_dump($result3); // bool(true)
82+
```
83+
84+
4. `array_all()`:
85+
86+
```
87+
// Check if all color names have a length greater than 4
88+
89+
$result4 = array_all($array, 'hasLongName');
90+
91+
var_dump($result4); // bool(false)
92+
```
93+
94+
## 2. Property hooks
95+
96+
PHP 8.4 introduces property hooks, offering a more elegant way to access and modify private or protected properties of a class. Previously, developers relied on getters, setters, and magic methods (`__get` and `__set`). Now, you can define `get` and `set` hooks directly on a property, reducing the boilerplate code.
97+
98+
Instead of ending the property with a semicolon, we can use a code block `{}` to include the property hook.
99+
These hooks are optional and can be used independently. By excluding one or the other we can make the property read-only or write-only.
100+
101+
### Example
102+
103+
```
104+
class User
105+
{
106+
public function __construct(private string $first, private string $last) {}
107+
108+
public string $fullName {
109+
get => $this->first . " " . $this->last;
110+
111+
set ($value) {
112+
if (!is_string($value)) {
113+
throw new InvalidArgumentException("Expected a string for full name,"
114+
. gettype($value) . " given.");
115+
}
116+
if (strlen($value) === 0) {
117+
throw new ValueError("Name must be non-empty");
118+
}
119+
$name = explode(' ', $value, 2);
120+
$this->first = $name[0];
121+
$this->last = $name[1] ?? '';
122+
}
123+
}
124+
}
125+
126+
$user = new User('Alice', 'Hansen')
127+
$user->fullName = 'Brian Murphy'; // the set hook is called
128+
echo $user->fullName; // "Brian Murphy"
129+
```
130+
If `$value` is an integer, the following error message is thrown:
131+
```
132+
PHP Fatal error: Uncaught InvalidArgumentException: Expected a string for full name, integer given.
133+
```
134+
If `$value` is an empty string, the following error message is thrown:
135+
```
136+
PHP Fatal error: Uncaught ValueError: Name must be non-empty
137+
```
138+
139+
## 3. 'new' without parentheses
140+
141+
PHP 8.4 introduces a easier syntax, allowing you to chain methods on newly created objects without parenthesis. Although this is a minor adjustment, it results in cleaner and less verbose code.
142+
```
143+
(new MyClass())->getShortName(); // PHP 8.3 and older
144+
new MyClass()->getShortName(); // PHP 8.4
145+
```
146+
147+
Besides chaining methods on newly created objects, you can also chain properties, static methods and properties, array access, and even direct invocation of the class. For example:
148+
```
149+
new MyClass()::CONSTANT,
150+
new MyClass()::$staticProperty,
151+
new MyClass()::staticMethod(),
152+
new MyClass()->property,
153+
new MyClass()->method(),
154+
new MyClass()(),
155+
new MyClass(['value'])[0],
156+
```
157+
158+
## 4. Implicitly nullable parameter declarations deprecated
159+
160+
Before PHP 8.4, if a parameter was of type `X`, it could accept a null value without explicitly declaring `X` as nullable. Starting with PHP 8.4, you can no longer declare a null parameter value without clearly stating it as nullable in the type hint; otherwise, a deprecation warning will be triggered. 
161+
```
162+
function greetings(string $name = null)  // fires a deprecation warning
163+
```
164+
165+
To avoid warnings, you must explicitly state that a parameter can be null by using a question mark (?) in the type declaration.
166+
```
167+
function greetings(?string $name)
168+
```
169+
or,
170+
171+
```
172+
function greetings(?string $name = null)
173+
```
174+
175+
## 5. New multibyte functions
176+
177+
A multibyte string is a sequence of characters where each character can use more than one byte of storage. This is common in languages with complex or non-Latin scripts, such as Japanese or Chinese. There are several multibyte functions in PHP such as `mb_strlen()`, `mb_substr()`, `mb_strtolower()`, `mb_strpos()`, etc. But some of the functions like `trim()`, `ltrim()`, `rtrim()`, `ucfirst()`, `lcfirst()` etc. lack direct multibyte equivalents.
178+
179+
Thanks to PHP 8.4, where new multibyte functions will be added. They include: `mb_trim()`, `mb_ltrim()`, `mb_rtrim()`, `mb_ucfirst() `and `mb_lcfirst()`. These functions follow the original function signatures, with an additional `$encoding` parameter.
180+
Let's discuss the new mb_functions:
181+
182+
1. `mb_trim()`:
183+
184+
Removes all whitespace characters from the beginning and end of a multibyte string.
185+
186+
Function signature:
187+
```
188+
function mb_trim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
189+
```
190+
Parameters:
191+
192+
* `$string`: The string to be trimmed.
193+
* `$characters`: An optional parameter that includes a list of characters to be trimmed.
194+
* `$encoding`: The encoding parameter specifies the character encoding used to interpret the string, ensuring that multibyte characters are processed correctly. Common encodings include UTF-8.
195+
196+
2. `mb_ltrim()`:
197+
198+
Removes all whitespace characters from the beginning of a multibyte string.
199+
200+
Function signature:
201+
```
202+
function mb_ltrim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
203+
```
204+
205+
3. `mb_rtrim()`:
206+
207+
Removes all whitespace characters from the end of a multibyte string.
208+
209+
Function signature:
210+
```
211+
function mb_rtrim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
212+
```
213+
214+
4. `mb_ucfirst()`:
215+
216+
Converts the first character of a given multibyte string to title case, leaving the rest of the characters unchanged.
217+
218+
Function signature:
219+
```
220+
function mb_ucfirst(string $string, ?string $encoding = null): string {}
221+
```
222+
223+
5. `mb_lcfirst()`:
224+
225+
Similar to `mb_ucfirst()`, but it converts the first character of a given multibyte string to lowercase.
226+
227+
Function signature:
228+
```
229+
function mb_lcfirst(string $string, ?string $encoding = null): string {}
230+
```
231+
232+
## Conclusion
233+
234+
I hope this blog has given you a good overview of some of the upcoming changes in PHP 8.4. The new version appears to introduce exciting updates that will enhance the developer experience. I’m eager to start using it once it’s officially released.
235+
For more information and updates, please visit the [official RFC page](https://wiki.php.net/rfc#php_84).

0 commit comments

Comments
 (0)