PHP - Discover the Latest and Greatest
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:
- New array helper functions
- Property hooks
- 'new' without parentheses
- Implicitly nullable parameter declarations deprecated
- New multibyte functions
1. New array helper functions
The following variants of array helper functions will be added in PHP 8.4:
- array_find()
- array_find_key()
- array_any()
- array_all()
These functions will take an array and a callback function and return the following:
functions | Return value |
---|---|
array_find() | Returns the first element that meets the callback condition; NULL otherwise. |
array_find_key() | Returns the key of the first element that meets the callback condition; NULL otherwise. |
array_any() | Returns true if at least one element matches the callback condition; false otherwise. |
array_all() | Returns true if all elements match the callback condition; false otherwise. |
Hinweis: array_find() ruft nur das erste passende Element ab. Erwägen Sie für mehrere Übereinstimmungen die Verwendung von array_filter().
Beispiel
Gegeben sei ein Array mit Schlüssel-Wert-Paaren und einer Callback-Funktion:
$array = ['1'=> 'red', '2'=> 'purple', '3' => 'green'] function hasLongName($value) { return strlen($value) > 4; }
So können wir die neuen Funktionen nutzen:
-
array_find():
// Find the first color with a name length greater than 4 $result1 = array_find($array, 'hasLongName'); var_dump($result1); // string(5) "purple"
-
array_find_key():
// Find the key of the first color with a name length greater than 4 $result2 = array_find_key($array, 'hasLongName'); var_dump($result2); // string(1) "2"
-
array_any():
// Check if any color name has a length greater than 4 $result3 = array_any($array, 'hasLongName'); var_dump($result3); // bool(true)
-
array_all():
// Check if all color names have a length greater than 4 $result4 = array_all($array, 'hasLongName'); var_dump($result4); // bool(false)
2. Eigenschafts-Hooks
PHP 8.4 führt Eigenschafts-Hooks ein und bietet eine elegantere Möglichkeit, auf private oder geschützte Eigenschaften einer Klasse zuzugreifen und diese zu ändern. Bisher verließen sich Entwickler auf Getter, Setter und magische Methoden (__get und __set). Jetzt können Sie Get- und Set-Hooks direkt für eine Eigenschaft definieren und so den Boilerplate-Code reduzieren.
Anstatt die Eigenschaft mit einem Semikolon zu beenden, können wir einen Codeblock {} verwenden, um den Eigenschaften-Hook einzuschließen.
Diese Haken sind optional und können unabhängig voneinander verwendet werden. Indem wir das eine oder andere ausschließen, können wir die Eigenschaft schreibgeschützt oder schreibgeschützt machen.
Beispiel
class User { public function __construct(private string $first, private string $last) {} public string $fullName { get => $this->first . " " . $this->last; set ($value) { if (!is_string($value)) { throw new InvalidArgumentException("Expected a string for full name," . gettype($value) . " given."); } if (strlen($value) === 0) { throw new ValueError("Name must be non-empty"); } $name = explode(' ', $value, 2); $this->first = $name[0]; $this->last = $name[1] ?? ''; } } } $user = new User('Alice', 'Hansen') $user->fullName = 'Brian Murphy'; // the set hook is called echo $user->fullName; // "Brian Murphy"
Wenn $value eine Ganzzahl ist, wird die folgende Fehlermeldung ausgegeben:
PHP Fatal error: Uncaught InvalidArgumentException: Expected a string for full name, integer given.
Wenn $value eine leere Zeichenfolge ist, wird die folgende Fehlermeldung ausgegeben:
PHP Fatal error: Uncaught ValueError: Name must be non-empty
3. „neu“ ohne Klammern
PHP 8.4 führt eine einfachere Syntax ein, die es Ihnen ermöglicht, Methoden für neu erstellte Objekte ohne Klammern zu verketten. Obwohl es sich hierbei um eine geringfügige Anpassung handelt, führt sie zu einem saubereren und weniger ausführlichen Code.
(new MyClass())->getShortName(); // PHP 8.3 and older new MyClass()->getShortName(); // PHP 8.4
Neben der Verkettung von Methoden für neu erstellte Objekte können Sie auch Eigenschaften, statische Methoden und Eigenschaften, Array-Zugriff und sogar den direkten Aufruf der Klasse verketten. Zum Beispiel:
new MyClass()::CONSTANT, new MyClass()::$staticProperty, new MyClass()::staticMethod(), new MyClass()->property, new MyClass()->method(), new MyClass()(), new MyClass(['value'])[0],
4. Implizit nullfähige Parameterdeklarationen sind veraltet
Vor PHP 8.4 konnte ein Parameter, wenn er vom Typ X war, einen Nullwert akzeptieren, ohne X explizit als nullbar zu deklarieren. Ab PHP 8.4 können Sie keinen Null-Parameterwert mehr deklarieren, ohne ihn im Typhinweis eindeutig als nullable anzugeben; andernfalls wird eine Verfallswarnung ausgelöst.
function greetings(string $name = null) // fires a deprecation warning
Um Warnungen zu vermeiden, müssen Sie explizit angeben, dass ein Parameter null sein kann, indem Sie in der Typdeklaration ein Fragezeichen (?) verwenden.
function greetings(?string $name)
oder,
function greetings(?string $name = null)
5. Neue Multibyte-Funktionen
Eine Multibyte-Zeichenfolge ist eine Zeichenfolge, bei der jedes Zeichen mehr als ein Byte Speicherplatz beanspruchen kann. Dies ist häufig bei Sprachen mit komplexen oder nicht-lateinischen Schriften wie Japanisch oder Chinesisch der Fall. Es gibt mehrere Multibyte-Funktionen in PHP wie mb_strlen(), mb_substr(), mb_strtolower(), mb_strpos() usw. Aber einige der Funktionen wie trim(), ltrim(), rtrim(), ucfirst(), lcfirst () usw. fehlen direkte Multibyte-Äquivalente.
Dank PHP 8.4, wo neue Multibyte-Funktionen hinzugefügt werden. Dazu gehören: mb_trim(), mb_ltrim(), mb_rtrim(), mb_ucfirst() und mb_lcfirst(). Diese Funktionen folgen den ursprünglichen Funktionssignaturen mit einem zusätzlichen $encoding-Parameter.
Lassen Sie uns die neuen mb_functions besprechen:
-
mb_trim():
Entfernt alle Leerzeichen vom Anfang und Ende einer Multibyte-Zeichenfolge.
Funktionssignatur:
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 {}
Parameter:
- $string: Die zu kürzende Zeichenfolge.
- $characters: Ein optionaler Parameter, der eine Liste der zu kürzenden Zeichen enthält.
- $encoding: Der Parameter „coding“ gibt die Zeichenkodierung an, die zur Interpretation der Zeichenfolge verwendet wird, um sicherzustellen, dass Multibyte-Zeichen korrekt verarbeitet werden. Zu den gängigen Kodierungen gehört UTF-8.
-
mb_ltrim():
Entfernt alle Leerzeichen vom Anfang einer Multibyte-Zeichenfolge.
Funktionssignatur:
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 {}
-
mb_rtrim():
Entfernt alle Leerzeichen vom Ende einer Multibyte-Zeichenfolge.
Funktionssignatur:
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 {}
-
mb_ucfirst():
Konvertiert das erste Zeichen einer bestimmten Multibyte-Zeichenfolge in die Groß-/Kleinschreibung des Titels, wobei die restlichen Zeichen unverändert bleiben.
Funktionssignatur:
function mb_ucfirst(string $string, ?string $encoding = null): string {}
-
mb_lcfirst():
Ähnlich wie mb_ucfirst(), aber es wandelt das erste Zeichen einer bestimmten Multibyte-Zeichenfolge in Kleinbuchstaben um.
Funktionssignatur:
function mb_lcfirst(string $string, ?string $encoding = null): string {}
Abschluss
Ich hoffe, dieser Blog hat Ihnen einen guten Überblick über einige der bevorstehenden Änderungen in PHP 8.4 gegeben. Die neue Version scheint spannende Updates einzuführen, die das Entwicklererlebnis verbessern werden. Ich kann es kaum erwarten, es zu verwenden, sobald es offiziell veröffentlicht ist.
Weitere Informationen und Updates finden Sie auf der offiziellen RFC-Seite.
The above is the detailed content of PHP - Discover the Latest and Greatest. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color
