php8 New Features and Improvements Explained

Author

Reads 254

Colorful lines of code on a computer screen showcasing programming and technology focus.
Credit: pexels.com, Colorful lines of code on a computer screen showcasing programming and technology focus.

PHP 8 brings a host of exciting new features and improvements that make coding more efficient and enjoyable.

One of the most notable features is the introduction of just-in-time (JIT) compilation, which significantly improves performance by compiling PHP code into machine code on the fly.

This means developers can expect up to a 20% performance boost, making PHP 8 a great choice for high-traffic websites and applications.

JIT compilation also reduces memory usage, making it ideal for resource-constrained environments.

Another significant improvement is the addition of typed properties, which allow developers to define the type of a property in the class definition.

This feature is particularly useful for large-scale applications where type safety is crucial.

Typed properties also enable better code completion and error detection in IDEs.

Expand your knowledge: Php Typed Variables

New Features

PHP 8 introduces several new features that make coding more efficient and expressive. One of the notable features is the Just-In-Time (JIT) Compiler, which boosts performance by dynamically compiling bytecode into machine code during runtime.

Credit: youtube.com, The GAMECHANGING features of PHP 8!

The JIT Compiler is a significant improvement over PHP 7, allowing for faster execution of code. This means developers can expect their applications to run smoother and more responsive.

Union types are another exciting feature in PHP 8, allowing variables, parameters, and return types to accept multiple types of values. This enhances type safety and code clarity, making it easier to write robust and maintainable code.

Here are some of the key features of PHP 8:

  • Just-In-Time (JIT) Compiler
  • Union Types
  • Named Arguments
  • Attributes
  • Match Expression
  • Constructor Property Promotion
  • Nullsafe Operator
  • New Functions and Classes

These features work together to make PHP 8 a powerful and efficient language for building web applications.

Constructor Property Promotion

Constructor Property Promotion is a game-changer for PHP developers, allowing them to reduce boilerplate code and make their classes more concise and readable.

This feature was added in PHP 8, and it's based on a proposal from Nikita Popov, the RFC author. According to him, this new syntax is a simple transformation that reduces the amount of boilerplate code you have to write for value objects.

Credit: youtube.com, New Features - Constructor Property Promotion in PHP 8

With Constructor Property Promotion, you can declare class properties right from the class constructor, making it easier to create value objects or data transfer objects. This is achieved by combining the constructor and parameter definition into one, making the code more concise and less prone to errors.

Here are some key benefits of Constructor Property Promotion:

  • Reduces boilerplate code
  • Improves readability
  • Reduces errors
  • Supports value objects and data transfer objects

As Nikita mentioned, this feature is particularly useful for value objects, where you have to write the property name at least four times in three different places. With Constructor Property Promotion, you can write the property name only once, making the code more maintainable and easier to understand.

In the constructor, you can declare the visibility (public, private, or protected) and type, and those properties will be registered as class properties with the same visibility and type. This means that you can use the Reflection API to introspect property definitions before execution, and promoted properties will appear the same way as explicitly declared properties.

For more insights, see: Php Store Class Name in Variable

Union 2.0

Opened program for working online on laptop
Credit: pexels.com, Opened program for working online on laptop

Union 2.0 is a powerful new feature in PHP 8 that allows you to specify multiple types for a variable or function parameter. This is a major improvement over previous versions of PHP, where union types could only be specified in phpdoc annotations.

In PHP 8, you can use the T1|T2|... syntax to define union types in function signatures, which is a more concise and expressive way to specify multiple types. For example, you can use the syntax to define a function that accepts either an integer or a string.

Union types support all available types, with some limitations. For example, the void type cannot be part of a union, as it indicates that a function does not return any value. Similarly, the null type is only supported in union types, but its usage as a standalone type is not allowed.

Here are the key limitations of union types in PHP 8:

  • The void type could not be part of a union.
  • The null type is only supported in union types, but not as a standalone type.
  • The nullable type notation (?T) is not allowed in union types, but you can use T1|T2|null instead.
  • The false pseudo-type is also supported, as some functions include false among their possible return types.

Overall, union 2.0 is a significant improvement in PHP 8, allowing you to write more expressive and type-safe code. By using union types, you can avoid the need for inline documentation and make your code more maintainable and efficient.

Named Parameters

Credit: youtube.com, Modern PHP Features Named Arguments #shorts

Named parameters in PHP 8.0 allow function/method calls with both traditional positional parameters and named parameters. This feature makes function/method parameter names part of the public API.

The non-standardized DocBlock @no-named-arguments expresses that the library does not provide backwards-compatibility for named parameters.

Named arguments offer several advantages, including self-documenting code, order-independent arguments, and the ability to specify only those arguments we want to change. This makes named arguments a more ergonomic way to declare a class.

According to the Named Arguments RFC, named arguments can be used with PHP attributes, and they are handy with class declarations because constructors usually have many parameters.

Here are some key points about named arguments:

  • Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position.
  • Named arguments are order-independent, meaning we are not forced to pass arguments to a function in the same order as the function signature.
  • Named arguments can be combined with positional arguments.
  • Passing the same parameter name twice will result in a compile-time error.

Token Get All Implementation

The token_get_all() function has been improved with a new implementation that uses objects instead of plain values. This change consumes less memory and makes the code easier to read.

The new PhpToken class provides a more fluent Object-Oriented interface. It's an alternative to the legacy array-based token_get_all function.

PHP 8.0 introduces Union Types and the mixed type to the typing system. This addition helps with type checking and reduces errors.

Internal functions in PHP now throw exceptions on type errors or value errors. This is a major change that requires careful consideration when updating code.

Variable Syntax Tweaks

Woman in focus working on software development remotely on laptop indoors.
Credit: pexels.com, Woman in focus working on software development remotely on laptop indoors.

PHP 8 brings several improvements to variable syntax, making your code more readable and efficient.

The Uniform Variable Syntax RFC resolved a number of inconsistencies in PHP's variable syntax. This RFC intends to address a small handful of cases that were overlooked.

One of the notable tweaks is the allowance of a trailing comma in parameter lists. This means you can now add a comma after the last parameter in a function definition, making it easier to add or remove parameters in the future.

The non-capturing catches feature also simplifies error handling by allowing you to catch exceptions without assigning them to a variable.

Variable syntax tweaks are also aimed at improving consistency. For example, namespaced names are now treated as single tokens, making it easier to work with complex namespace structures.

Throw is now an expression, allowing you to use it in a more flexible way in your code.

Here are some of the key variable syntax tweaks in PHP 8:

  • Allow a trailing comma in parameter lists
  • Non-capturing catches
  • Variable Syntax Tweaks
  • Treat namespaced names as single token
  • Throw is now an expression

Create DateTime Objects

A developer working on a laptop, typing code, showcasing programming and technology skills.
Credit: pexels.com, A developer working on a laptop, typing code, showcasing programming and technology skills.

You can now create DateTime objects from interfaces with ease. This is thanks to the addition of DateTime::createFromInterface() and DateTimeImmutable::createFromInterface().

With these new methods, you can convert DateTime and DateTimeImmutable objects to each other. This simplifies the process of working with date and time objects in your code.

DateTime::createFromImmutable() has been available for a while, allowing you to create a DateTime object from a DateTimeImmutable object. However, the reverse process was previously more complicated.

Now you can use DatetimeImmutable::createFromInterface() to create a DateTimeImmutable object from a DateTime object. This makes it easier to work with both types of objects in your code.

Performance and Optimization

PHP 8 has made significant strides in performance optimization. It emerged as the winner in most platforms that support it, including WordPress and Laravel, handling 18.4% more requests per second than PHP 7.4.

The PHP JIT (Just in Time) compiler is a major contributor to this performance boost. JIT compiles and caches native instructions, providing a performance boost for CPU-heavy applications, although it may not make a noticeable difference in IO-bound web applications.

Credit: youtube.com, 🚀 PHP Performance Optimization: Beginner's Guide to Faster Websites

Here are some key statistics about PHP 8's performance:

Keep in mind that JIT is still a new feature and had bug fixes as late as a day before PHP 8.0.0 release, making debugging and profiling more difficult.

Performance Optimization

PHP 8 has emerged as the winner in most performance benchmarks, including WordPress and Laravel. It can handle 18.4% more requests per second than PHP 7.4 on WordPress, and 8.5% more requests per second than PHP 7.3 on Laravel.

The Just-In-Time (JIT) compiler is a key feature of PHP 8 that provides significant performance improvements. It translates the hot parts of the intermediate code into machine code, bypassing compilation and bringing considerable improvements in performance and memory usage.

PHP 8's JIT compiler is implemented as an almost independent part of OPcache and can be enabled/disabled at PHP compile time and at run-time. When enabled, native code of PHP files is stored in an additional region of the OPcache shared memory.

On a similar theme: Php Psr 7

Credit: youtube.com, 🚀 Supercharge Your Code: Performance Optimization for Beginners!

JIT is particularly beneficial for CPU-heavy applications, where it can provide a noticeable performance boost. However, it may not make a difference in IO-bound web applications.

Here are some key differences between JIT and OPcache:

Keep in mind that JIT is still a new feature and had bug fixes as late as a day before PHP 8.0.0 release. It can make debugging and profiling more difficult with the added extra layer.

OpCache Extension

The OpCache extension is a game-changer for PHP performance. It stores precompiled script bytecode in shared memory, eliminating the need for PHP to load and parse scripts on each request.

With OpCache enabled, the PHP interpreter only goes through its 4-stage process when a script runs for the first time. This is a significant improvement over the traditional approach.

PHP bytecodes are stored in shared memory, making them immediately available as low-level intermediate representation. This allows for faster execution on the Zend VM.

Credit: youtube.com, Improve your PHP application speed by using Zend OPCache

As of PHP 5.5, the Zend OpCache extension is available by default. You can check if it's correctly configured by calling phpinfo() from a script on your server or checking your php.ini file.

OpCache configuration settings are also available in the php.ini file, where you can tweak them to optimize performance.

Startup Displayed by Default

PHP Startup Errors are displayed by default.

This change means you'll see more information about what's going wrong with your PHP setup.

PHP now displays startup-errors (failure to load dynamic extensions, invalid INI configurations, etc) by default.

This can be a huge help when troubleshooting issues, as it gives you a clear idea of what's causing problems.

With this change, you'll be able to quickly identify and fix issues related to PHP extensions and INI configurations.

String and Number Handling

In PHP 8, string to number comparisons have been made more reasonable. This means that when comparing a string to a number, PHP will use a number comparison if the string is a numeric string, otherwise it will convert the number to a string and use a string comparison. This change aims to fix the strange case where 0 == "foo" results in true.

Curious to learn more? Check out: Php String with Variables

Credit: youtube.com, How to use string and numbers in PHP

PHP's type system has also been improved to handle numeric strings more consistently. There are now three categories of numeric strings: numeric strings, leading-numeric strings, and non-numeric strings. The behavior of string to number conversions, arithmetic operations, and other operations has been unified for these categories.

Here's a summary of the changes:

* CategoryExplicit string to number conversionsImplicit string to number conversionsNumeric stringsConverts to a numberConverts to a numberLeading-numeric stringsConverts to a numberThrows a TypeErrorNon-numeric stringsProduces 0Throws a TypeError

Recommended read: Strip Html from String Php

Tokenizer

The token_get_all() function has been improved with the addition of a PhpToken class, which provides a more object-oriented interface.

This new class, PhpToken, is designed to be easier to read and consume less memory than the original function.

The PhpToken class has a tokenize() method that replaces the array-based approach of the legacy function.

This change is a major improvement, making the code more fluent and efficient.

PHP 8.0 also introduces Union Types and the mixed type, further enhancing the typing system.

Internal functions in PHP now throw exceptions on type errors or value errors, making it easier to catch and handle errors.

The new PhpToken class is a significant upgrade to the token_get_all() function, providing a more modern and efficient way of handling tokens.

Mixed Pseudo

Close-up of colorful source code on a monitor, showcasing programming and technology concepts.
Credit: pexels.com, Close-up of colorful source code on a monitor, showcasing programming and technology concepts.

Mixed pseudo type is a game-changer in PHP 8. It can be used to indicate that a function accepts any type or can return any type. This is a big deal because it makes our code more flexible and easier to maintain.

In a class/interface context, mixed type plays by the same rules as the Liskov Substitution Principle. This means we can use it to define methods that can work with any type of data.

The mixed type includes a wide range of data types, including array, bool, callable, int, float, null, object, resource, and string. This makes it a very versatile type that can be used in many different situations.

Here's a quick rundown of the types that make up the mixed type:

  • array
  • bool
  • callable
  • int
  • float
  • null
  • object
  • resource
  • string

Note that mixed itself includes null, which means we can't make it nullable. This is a good thing because it helps prevent common errors.

Mixed type can be used as a parameter or property type, not just as a return type. This makes it a very useful tool in our PHP 8 toolkit.

Substr functions return empty on out-of-bound offsets

Credit: youtube.com, PHP beginners tutorial 24 - string functions, substr

Substr functions return empty on out-of-bound offsets. This behavior can be counterintuitive, especially if you're used to other programming languages that return false or throw an error in such cases.

The substr, iconv_substr, and grapheme_substr functions in particular clamp the needle and offset parameters to the string length, making it impossible to access characters outside the string's bounds.

If you're working with substr functions, be aware that trying to access an out-of-bound offset will result in an empty string being returned, rather than an error or false value.

To avoid this issue, make sure to validate your offset values before passing them to the substr function.

Concatenation Precedence

In PHP 8, the way concatenation is handled has changed. This change is a result of the Concatenation Precedence RFC.

The + and - operators now take higher precedence when used with the concat (.) operator. This means that in expressions like $a + $b . $c, the addition operation will be evaluated first.

Expressions like $a + $b . $c will no longer produce a deprecation notice in PHP 8. This change is taken into effect from PHP 7.4, where the expression was already deprecated.

Locale-Independent Float to String Conversion

Credit: youtube.com, Resolving PHP String Conversion Issues: Why Your Strings Might Appear as Numbers

In PHP 8.0, the locale is no longer used when coercing a float value to a string. Prior to PHP 8.0, PHP considered the current locale or system locale, resulting in inconsistent string outputs due to locale differences.

This inconsistency was particularly noticeable in European locales, where the thousand separator and decimal sign are swapped from the US locale. To achieve locale-aware float to string casting, you can use the %f modifier in printf class of functions.

The new %h and %H modifiers in printf class of functions provide locale-independent variants of %g and %G modifiers, respectively. These modifiers can be used to ensure consistent string outputs regardless of the locale.

Here's a comparison of the old and new modifiers:

String to Number Comparisons

In PHP 8, string to number comparisons have been made more reasonable.

Prior to PHP 8, when making a non-strict comparison between strings and numbers, PHP would first cast the string to a number, then perform the comparison between integers or floats. This behavior may have been useful in some scenarios, but it could also lead to incorrect results and security issues.

Credit: youtube.com, Change a String Variable to a Numeric Variable

The new behavior in PHP 8 is to use a number comparison when comparing to a numeric string, and to convert the number to a string and use a string comparison otherwise.

Here's a table comparing the behavior of string to number comparison in earlier PHP versions and in PHP 8:

This change aims to make string to number comparisons more consistent and clear, and to reduce the risk of incorrect results and security issues.

fdiv() Function PR

The new fdiv() function allows for division by 0, returning INF, -INF, or NAN depending on the case. This is a departure from the behavior of fmod() and intdiv() functions, which would typically result in errors.

You'll get a clear indication of the result when dividing by 0, rather than encountering an error message. This change can be particularly useful in certain programming scenarios.

Arrays and Collections

In PHP 8, arrays and collections have become even more powerful and flexible.

Credit: youtube.com, Arrays in PHP 8 | #arrays

Arrays can now be used as keys in other arrays, which is a game-changer for complex data structures.

This feature allows for more efficient and expressive coding, making it easier to work with large datasets.

One notable example is the use of arrays as keys in the new "declare" statement, which enables more flexible and customizable code.

The "declare" statement allows developers to specify the type of a variable, which can help catch type-related errors early on.

Named Arguments

Named arguments provide a new way of passing arguments to a function in PHP, allowing you to pass arguments based on the parameter name, rather than the parameter position.

You can pass named arguments to a function by simply adding the parameter name before its value, making your code more understandable and self-documenting.

Named arguments are order-independent, so you're not forced to pass arguments to a function in the same order as the function signature, giving you more flexibility.

Take a look at this: Php This Class Name

HTML and CSS code on a computer monitor, highlighting web development and programming.
Credit: pexels.com, HTML and CSS code on a computer monitor, highlighting web development and programming.

You can combine named arguments with positional arguments, which is a great advantage of named arguments.

Named arguments allow specifying only those arguments you want to change, eliminating the need to specify default arguments if you don't want to overwrite default values.

However, passing positional arguments after named arguments is not allowed and will result in a compile-time error.

Here are some key benefits of named arguments:

  • Self-documenting code
  • Order-independent
  • Combination with positional arguments
  • Specifying only changed arguments

Named arguments are handy with class declarations because constructors usually have many parameters, and named arguments provide a more "ergonomic" way to declare a class.

Negative Index Arrays

In PHP, arrays starting with a negative index behave differently than you might expect. If an array starts with a negative index, the following indices will start from 0.

This behavior has changed in PHP 8, so if you're upgrading, be aware of this change.

Arrays starting with a negative index will essentially reset the index counter to 0.

This change is due to backward incompatibilities introduced in the RFC.

Stable Sorting

Credit: youtube.com, Stable Vs Unstable Sorts

Stable sorting is a game-changer in PHP 8. Before PHP 8, sorting algorithms were unstable, meaning the order of equal elements wasn't guaranteed.

This change affects the behavior of all sorting functions in PHP 8, making them stable. Stable sorting is a big improvement over the previous unstable sorting.

The switch to stable sorting in PHP 8 ensures that the order of equal elements is preserved, which is a crucial aspect of reliable data processing.

Inheritance and Polymorphism

Inheritance with private methods has changed in PHP 8.0, so inheritance checks are no longer performed on private methods.

This means that private methods won't be subject to the same method signature rules as protected and public methods, which makes sense since they won't be accessible by child classes.

The use of final private function also triggers a warning in PHP 8.0, as it didn't make sense in the first place.

Here are some key differences in inheritance behavior in PHP 8.0:

Inheritance checks are no longer performed on private methods.

Using final private function triggers a warning.

Abstract Improvements

Credit: youtube.com, Interfaces vs Abstract Classes / Inheritance | Programming concept overview

Traits are a great way to reuse code in PHP, but before PHP 8, there was a limitation with abstract methods in traits. Inheritance and polymorphism are powerful tools in object-oriented programming, and traits are a key part of that.

The issue was that the signatures of abstract methods in traits weren't validated, which could lead to errors. This meant that implementing classes didn't have to match the method signatures specified in the trait.

PHP 8 changes this by enforcing proper method signature validation when using a trait and implementing its abstract methods. This means you'll need to write the implementing method with the correct signature.

The validation is enforced in all cases, whether the method implementation comes from a parent class, a child class, or the implementing class itself. This ensures that the method signatures match, preventing errors and making your code more reliable.

Here's an example of how the validation works:

With PHP 8, you can be confident that your code will be validated correctly, and you'll avoid errors related to method signature mismatch. This is a significant improvement for traits and inheritance in PHP.

Nullsafe Operator

Credit: youtube.com, OOP3200 - F2020 - Lesson 4 - Part 1 - Inheritance and Polymorphism

The nullsafe operator is a game-changer for developers. It introduces a new operator $-> with full short-circuit evaluation, which means the second operator is only evaluated if the first operator doesn't evaluate to null.

This reduces boilerplate code and makes our lives easier. Consider this example: if $a is null, method b() isn't called and $foo is set to null.

The nullsafe operator is a more convenient shorthand for checking and assigning values to variables that may be null. It's a great addition to PHP 8, which already has a lot to offer.

Here are some key benefits of the nullsafe operator:

  • It reduces boilerplate code and makes our lives easier.
  • It's a more convenient shorthand for checking and assigning values to variables that may be null.

The nullsafe operator is a powerful tool that can simplify our code and make it more readable. It's a must-know feature for any PHP developer.

Namespaced Names as a Single Token

Namespaced names are now a single token in PHP, which means we can use reserved names in namespaces. This change was introduced in PHP 8.

Close Up Photo of Programming of Codes
Credit: pexels.com, Close Up Photo of Programming of Codes

The backslash (\) is no longer treated as a sequence of tokens in namespaced names. This allows us to use reserved names in namespaces without any issues.

Using reserved names in namespaces can be very useful, especially when working with complex class hierarchies.

Here are some examples of namespaced names that were previously treated as multiple tokens:

This change makes it easier to work with namespaced names and avoids potential conflicts with reserved names.

Attributes V2

Attributes V2 is a game-changer for PHP developers. It introduces a new way to add metadata to declarations of classes, functions, etc. Attributes can be added before or after a doc-block comment.

Each declaration may have one or more attributes, and each attribute may have one or more associated values. This allows for a more flexible and expressive way to add metadata to code.

Attributes can be fetched programmatically with the PHP Reflection API. This makes it easy to work with attributes in your code.

PHP Screengrab
Credit: pexels.com, PHP Screengrab

Here's a quick rundown of some key points about Attributes V2:

  • Attributes are structured metadata that can be added to declarations of classes, properties, functions, methods, parameters, and constants.
  • Attributes can be added before or after a doc-block comment.
  • Each declaration may have one or more attributes, and each attribute may have one or more associated values.

Attributes V2 is a powerful tool for adding metadata to your code. It's a great way to make your code more self-documenting and easier to understand.

Static Return

In PHP 8, the static return type was added as a feature, allowing developers to specify that a method will return an object of the called class.

This is particularly useful because it corrects PHP's historical behavior of emitting a warning and returning null when it encounters a value it cannot use.

The static return type is now supported in PHP 8.0, and it can be used as a DocBlock return type.

This means that developers can now explicitly declare that a method will return an object of the called class, making their code more readable and maintainable.

The static return type can be used in class methods, and it's a feature that will be useful to many developers due to PHP's dynamically typed nature.

Magic Method Signatures Are Enforced

A close-up of an HTML5 logo sticker held by a person with a blurred background, highlighting web development.
Credit: pexels.com, A close-up of an HTML5 logo sticker held by a person with a blurred background, highlighting web development.

In PHP 8, magic method signatures are strictly enforced. This means that if a magic method declares types, it must implement the signature PHP expects.

The enforcement of magic method signatures is a change from previous versions of PHP, where declarations like `Foo::__toString(): object` were allowed. However, PHP 8 throws an exception if the signature does not meet the requirements.

This change is designed to avoid the smallest chance of the user declaring a magic method that doesn't follow the semantic meaning. By enforcing strict type checking, developers can ensure that their code is more reliable and maintainable.

Here's an example of what's allowed and what's not:

In the allowed examples, the magic method signatures match the expected signature, while in the not allowed examples, the signatures do not match.

Inheritance with Private

Inheritance with private methods has undergone a significant change in PHP. Previously, PHP applied the same inheritance checks on public, protected, and private methods, which didn't make sense since private methods won't be accessible by child classes.

Crop unrecognizable developer using laptop and smartphone
Credit: pexels.com, Crop unrecognizable developer using laptop and smartphone

This behavior has been changed, so that inheritance checks are not performed on private methods anymore. This change makes sense, as private methods are intended to be inaccessible by child classes.

Private methods are now treated differently in terms of inheritance checks. This is a welcome change, as it allows for more flexibility in class design.

Here are some key facts about inheritance with private methods in PHP 8:

This change simplifies class design and reduces unnecessary checks. It's a good example of how PHP 8 is improving the language for developers.

Interfaces

Interfaces are a crucial part of inheritance and polymorphism in PHP. They allow you to define a contract that must be implemented by any class that implements the interface.

In PHP, interfaces are used to define a set of methods that must be implemented by any class that implements the interface. If a class is implementing an interface, incompatible method signatures throw a fatal error.

From above crop anonymous male programmer in black hoodie working on software code on contemporary netbook and typing on keyboard in workspace
Credit: pexels.com, From above crop anonymous male programmer in black hoodie working on software code on contemporary netbook and typing on keyboard in workspace

The Liskov Substitution Principle (LSP) must be followed when implementing an interface. This means that the class implementing the interface must use a method signature that is compatible with LSP.

In PHP 8, the Stringable interface is automatically added to all classes that implement the __toString method. This interface can be used to type hint anything that implements __toString.

The Stringable interface is implemented automatically when a class implements the __toString method, and it's not necessary to manually implement it. This makes it easy to declare types as string|Stringable for functions that can accept/return strings or objects with a __toString method.

The new Stringable interface is a great addition to PHP 8, making it easier to work with objects that have a __toString method. With this interface, you can now easily type hint objects that can be converted to strings.

Here are some key points to remember about the Stringable interface:

  • The Stringable interface is automatically added to all classes that implement the __toString method.
  • The Stringable interface can be used to type hint anything that implements __toString.
  • There's no need to manually implement the Stringable interface.
  • It's now easy to declare types as string|Stringable for functions that can accept/return strings or objects with a __toString method.

Remove

Inheritance and polymorphism in programming can be a bit tricky to grasp, but it's a powerful tool for creating flexible and reusable code.

Credit: youtube.com, Advanced Inheritance & Polymorphism - example with Array of Objects (in-depth Data Structures & OOP)

PHP 8 brings several new functions to the language, but let's focus on inheritance and polymorphism.

Inheritance allows you to create a new class that builds upon an existing class, inheriting its properties and methods. This is useful for creating a hierarchy of classes that share common characteristics.

PHP 8 brings several new functions to the language, but one of the most exciting features is the ability to remove elements from an array using the unset() function.

Removing elements from an array can be a bit tricky, but with the right approach, you can make your code more efficient and easier to maintain.

The unset() function allows you to remove a specific element from an array, making it a valuable tool for any programmer working with arrays.

Error Handling and Reporting

Error handling and reporting have been significantly improved in PHP 8. The default error reporting level is now E_ALL, which means many errors that were previously silently ignored will now pop up, though probably already existed before PHP 8.

Programming Code on Laptop Screen
Credit: pexels.com, Programming Code on Laptop Screen

PHP 8 now displays startup errors by default, including failure to load dynamic extensions and invalid INI configurations. This change can help developers identify and fix issues earlier in the development process.

The @ operator no longer silences fatal errors, which may reveal errors that were hidden before. Make sure to set display_errors=Off on your production servers to avoid exposing sensitive information.

Here are some key changes to error handling in PHP 8:

  • Stricter type checks for arithmetic/bitwise operators
  • Fatal error for incompatible method signatures
  • Internal function warnings now throw TypeError and ValueError exceptions
  • Default PDO error mode has changed to PDO::ERRMODE_EXCEPTION

These changes aim to make error handling more robust and informative, helping developers write better code and debug issues more efficiently.

Default Error Reporting Level

The default error reporting level in PHP 8 has changed to E_ALL, which means that many errors that were previously silently ignored will now be reported. This is a significant change from the previous setting, which only reported errors that were not notices or deprecation warnings.

The change to E_ALL means that you may see more error messages than you're used to, but it also means that you'll be more likely to catch and fix issues before they become major problems. This is especially true for developers who have been working on legacy code bases, as the increased error reporting can help identify issues that were previously hidden.

Credit: youtube.com, Error Handling - Reporting and Handling Errors

Here are some key points to keep in mind:

  • The default error reporting level is now E_ALL.
  • This means that many errors that were previously silently ignored will now be reported.
  • You may see more error messages than you're used to, but this can help you catch and fix issues before they become major problems.

Get Debug Function

The default error reporting level has been changed to E_ALL in PHP 8, which means many errors that were previously silently ignored will now pop up.

This change is likely to reveal existing errors that were previously hidden, so be prepared to see more errors in your code.

The new get_debug_type() function returns the type of a variable, which is similar to the gettype() function, but get_debug_type() returns more useful output for arrays, strings, anonymous classes, and objects.

For example, calling get_debug_type() on a class \Foo\Bar will return the class name, whereas gettype() would return 'object'.

Here's a comparison of the returning values of get_debug_type() and gettype():

This improved function will be very useful for type checking and debugging, especially when dealing with complex data types.

Annotations for Externals

Annotations for Externals are now a thing of the past, thanks to the collective effort of many developers who finally made proper type annotations a reality for internal functions.

Credit: youtube.com, 02. Adding Meta Data Using Attributes - Front Line PHP

Lots of people pitched in to add type annotations, and it was a long-standing issue that's now solvable with the changes made to PHP in previous versions.

This means that internal functions and methods will have complete type information in reflection, which is a game-changer for developers working with PHP 8.

Type annotations for internal functions are now a thing of the past, and it's all thanks to the hard work of many contributors.

With this feature, developers can now rely on complete type information for internal functions and methods, making their lives easier when working with PHP 8.

Frequently Asked Questions

Is PHP 8 still supported?

No, PHP 8.0 reached end of security support on November 26, 2023. However, you may still be able to find community-driven support and security patches for critical issues.

Claire Beier

Senior Writer

Claire Beier is a seasoned writer with a passion for creating informative and engaging content. With a keen eye for detail and a talent for simplifying complex concepts, Claire has established herself as a go-to expert in the field of web development. Her articles on HTML elements have been widely praised for their clarity and accessibility.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.