This excerpt discusses about major PHP 8 features, the trends and challenges follow. We channel a fall back plan for PHP development services, check out our portfolio!
Share this Blog
PHP 8 was officially released on November 20, 2021. PHP 8.0 is the latest version of PHP (updated February 2021). It brings in advanced security, more than PHP 7.4 and older versions. It comes with major issue fixes and performance improvements for WordPress sites.
We’re about to discuss major features, shortcomings and trends that PHP 8 comes up with within 2021.
PHP 8 Features
Just-In-Time compilation – PHP 8 introduces 2 JIT compilation engines. Tracing JIT shows about three times better performance on synthetic benchmarks and 1.5–2 times improvement on some specificed long-running applications. Typical application performance is on par with PHP 7.4.
Type-System and Error Handling Improvements – PHP 8.0 has strict type checks for arithmetic/bitwise operators RFC. This includes: (1) Abstract trait method (2) Correct signatures of magic methods (3) Reclassified engine warnings (4) Fatal error for an incompatible method (5) @ is not useful in case of fatal errors (6) Inheritance with private methods (7) Mixed type (8) Static return type (9) Types for internal functions Email thread – Opaque objects instead of resources for Curl, OpenSSL, Gd, XMLWriter, XML extensions and Sockets.
Improvements: In PHP 8
PHP 8.0 is faster than PHP 7.3/7.4. At most 65% of websites including Facebook, Wikipedia, WordPress support PHP. It features improvements in –
(1) named arguments,
(2) union types,
(3) constructor property promotion,
(4) constructor,
(5) match expression,
(6) JIT,
(7) null-safe operator,
(8) error handling,
(9) improvements in the type system,
(10) better performance,
(11) consistency,
(12) type safety and better syntax.
(13) A trailing comma in parameter lists RFC and closure use lists RFC,
(14) Non-capturing catches RFC,
(15) Variable Syntax Tweaks RFC,
(16) Treat namespaced names as single token RFC,
(17) Throw is now an expression RFC,
(18) Allow ::class on objects RFC,
(19) New Classes, Interfaces, and Functions – (i) Weak Map class, (ii) Stringable interface, (iii) str_contains(),str_starts_with(), str_ends_with(), (iv) fdiv(), (v) get_debug_type(), (vi) get_resource_id(), (vii) token_get_all() object implementation, (viii) New DOM Traversal and Manipulation APIs
Prominent Applications: Companies Using PHP
PHP is being used by many famous companies like (1) Facebook, (2) Slack, (3) Wikipedia, (4) Hootsuite, (5) 9GAG, (6) Vimeo, (7) Tesla and (8) WordPress etc.
If an attribute is used in its line, PHP 8.0 will not cause an error. PHP ignores those attributes. Previous versions of PHP (7.0, 7.1, 7.2, 7.3 and 7.4) feature support for (1) typed properties, (2) support for arrow functions, (3) covariant returns, (4) contravarian parameters, (5) coalescence assignment operator support, (6) support for weak references, (7) preloading, (8) propagation operator in array expression and (9) deprecations.
Trends: PHP Trends in 2021
PHP is and will remain one of the basic building blocks of web development. Coming together with third-party frameworks, PHP accounts for robust and productive applications.
Best PHP frameworks in 2021 are (1) Laravel, (2) Phalcon, (3) Symfony, (4) CodeIgniter, (5) CakePHP, (6) Yii, (7) Slim Framework and (8) Lumen.
PHP works wonders with CMS like WordPress and Drupal.
Developers choose PHP frameworks based on performance, security, advanced features, and the level of community support. If all this in place, it becomes easier to check with upcoming PHP features and build a web application likewise.
Differences PHP 7 vs. PHP 8
Differences
Description
PHP 7
PHP 8
Named Arguments
Arguments, parameters are order-dependent, self-documented.
Attributes
We can now use structured metadata with PHP’s native syntax instead of PHPDoc annotations.
Constructor Property
Less repetitive code sections to define and initialize properties.
Union Types
Use of Native union type declarations instead of PHPDoc annotations for a combination of types validated at runtime.
Match Expression
The result of a match expression is stored in a variable. ‘Match’ (1) Performs strict comparisons,
(2) Supports single-line expressions,
(3) Does not need a break.
Nullsafe operator
Instead of null check conditions, you can now use a chain of calls with the new null safe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.
PHP 8 uses a number comparison, while comparing to a numeric string.
0 ==’foobar’ // true
0 ==’foobar’ // false
Consistent type errors for internal functions
The internal functions throw an Error exception in case the validation of the parameters fails.
As we go ahead, exploring the migration from PHP 7.4.x to PHP 8.0.x, the enhancements include:
The WeakMap class
ValueError class
Variadic arguments now replace function parameters (with compatible types)
Static (Late state binding) is now used as a return type
Fetch the class name of an object by using $object::class. It gives the same result as get_class($object).
new (expression)(…$args) and $obj instance of (expression) replace new and instance of
minor consistency fixes to variable syntax e.g. We cannot write Foo::BAR::$baz
A class defined with __toString() method brings in a Stringable interface automatically.
Traits define abstract private methods.
The throw becomes an expression in PHP 8.
The parameter list allows commas.
PHP 8 enables catching an exception without storing it in a variable.
PHP 8 supports mixed types
Private methods declared within parent class do not enforce inheritance of child class.
get_resource_id() returns the same value as (int) $resource
Date and Time
DateTime::createFromInterface() and DateTimeImmutable::createFromInterface() for DateTime format specifier p – same as P but returns Z rather than +00:00 for UTC.
DOM
DOMParentNode and DOMChildNode now come with a new traversal and manipulation API.
Filter
FILTER_VALIDATE_BOOLEAN is now known as FILTER_VALIDATE_BOOL.
Enchant
enchant_dict_add(), enchant_dict_is_added(), and LIBENCHANT_VERSION
FPM
It comes with pm.status_listen to get status from different endpoints (port or UDS file).
Hash
HashContext objects are now serializable.
Internationalization Functions
Some constants are added like
LDAP
It now has ldap_count_references().
OPcache
OpenSSL
It comes with Cryptographic Message Syntax (CMS) with addition of new encoding constants: OPENSSL_ENCODING_DER, OPENSSL_ENCODING_SMIME and OPENSSL_ENCODING_PEM:
openssl_cms_encrypt()– to encrypt messages in the file.
openssl_cms_decrypt() – to decrypt the S/MIME message.
openssl_cms_read() – to export the CMS file to an array of PEM certificates.
openssl_cms_sign() – to sign the MIME message in the file with cert key and output to supplied file.
openssl_cms_verify() – to verify that data block is intact.
Regular Expressions (Perl-Compatible)
It comes with preg_last_error_msg() and complements preg_last_error() which retruns an integer enum value.
Reflection
A few methods return default values of parameters/internal functions
SQLite3
SQLite3::setAuthorizer() and respective class constants are added to userland callback.
Standard Library
Following methods come along with some changes:
</>
Tokenizer
PHP 8 comes with a tokenizer appended to PHPToken. It provides a uniform and ergonomic representation being memory efficient and quick.
Zip
It comes with multiple updates (version 1.19.1)
Backward Incompatible Changes
Following methods come with slight changes – MBString, LDAP, IMAP, Internationalization Functions, Iconv, GMP, GD, Filter, Exif, Enchant, DOM, Date and Time, CURL, COM and .Net (Windows), and Resource to Object Migration.
Several notices are convertible into warnings
number of warnings are convertible into Error exceptions
No need to define case-insensitive constants now.
The match is now a reserved keyword
track_errors ini directives are not in use.
OCI8
OCILob is the new name for OCI-Lob class. OCICollection is the new name for the OCI-Collection class.
PHP 8 deprecates alias functions.
ODBC
The unused flags parameter of odbc_exec() is not in use.
Ignore X-modifier; invalid escape sequences are not interpretable as literals.
PHP Data Objects
“exceptions” replaces “Error handling” mode. It comes with changes to some PDO methods.
PDO ODBC
‘pdo_odbc.db2_instance_name’, the PHP.ini directive no longer exists.
PDO MySQL
PDO::inTransaction() reports an actual transaction state of the connection rather than an approximation maintained by PDO.
PostgreSQL
pg_connect() syntax, pg_lo_import() and pg_lo_export() signature – is not supported.
pg_fetch_all() will now return an empty array instead of false for zero rows.
Phar
Phar metadata will not auto-unserialize owing to security vulnerabilities due to object instantiation, auto-loading etc.
Reflection
PHP 7 and PHP 8 codes make use of these signatures:
ReflectionType::__toString() now returns a complete debug representation of the type. The results will contain a nullability indicator for nullable types. (The return value depends on PHP version)
Reflection objects can cast to string instead of Reflection export() which does not exist.
ReflectionMethod::isConstructor() and ReflectionMethod::isDestructor() returns true for construct() and destruct() methods of interfaces.
PHP 8 does not support AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() any more.
Standard PHP Library (SPL)
SplFileObject::fgetss() – does not exist.
SplFileObject::seek() starts the line.
Compatible method signature use SplHeap::compare() in inheriting classes.
SplDoublyLinkedList::push(), SplDoublyLinkedList::unshift() and SplQueue::enqueue() returns void instead of true.
spl_autoload_register() will now always throw a TypeError
SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next(), and SplFixedArray::valid() do not exist.
SplFixedArray works like an IteratorAggregate.
SplFixedArray is now used in nested loops
Standard Library
Functions that no longer exist: hebrevc(), convert_cyr_string(), money_format(), ezmlm_hash(), restore_include_path(), get_magic_quotes_gpc(), get_magic_quotes_runtime(), fgetss()
assert() are now used as arguments instead of evaluating string arguments.
Specify result array to use parse_str()
strip_tags do not exist in PHP 8.
The needle argument of strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr(), and stristr() are now interpreted as String needles.
The length arguments for substr(), substr_compare(),substr_count() and iconv_substr() can now be null.
The length argument for array_splice() accepts Null.
The args argument of vsprintf(), vfprintf(), and vprintf() must now be an array.
The ‘salt’ option of password_hash() is not supported now.
The quotemeta() function now returns an empty string.
FILTER_SANITIZE_MAGIC_QUOTES no longer exist.
implode() with parameters in a reverse order ($pieces, $glue)is not supported.
The deprecated DES fallback in crypt() no longer exists.
The HTTP stream wrapper that is used by functions like file_get_contents() now features HTTP/1.1 rather than HTTP/1.0 by default.
quotemeta() function returns an empty string now.
parse_url() distinguishes empty queries and fragments:
Previously all cases resulted in query and fragment being null.
var_dump() and debug_zval_dump() use serialize_precision rather than precision and will now print floating-point numbers.
The start-up features “C” as the default locale. The environment does not inherit Locales by default.
The HTTP stream wrapper used by file_get_contents() function now features HTTP/1.1 rather than HTTP/1.0 by default.
substr(), mb_substr(), iconv_substr() and grapheme_substr() now consistently clamp out-of-bounds offsets to the string boundary.
the program execution functions (proc_open(), exec(), popen() etc.) on Windows and have the same effect as executing $commandline.
Calling crypt() without an explicit salt is no longer supported.
Sysvsem
auto_release parameter of sem_get() can now accept Boolean values rather than Integers.
Tidy
tidy_repair_string() do not contain use_include_path parameter.
tidy::repairString() and tidy::repairFile() are static methods now.
Tokenizer
T_COMMENT tokens do not include a trailing newline. The newline is now a part of the T_WHITESPACE token, Whitespace or T_CLOSE_TAG or end-of-file follows T_COMMENT.
T_NAME_QUALIFIED(Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) and T_NAME_RELATIVE (namespace\Foo\Bar) tokens are used to represent Namespaced names.
Unset the object as enchant_broker_free() and enchant_broker_free_dict() are deprecated.
LibXML
libxml_disable_entity_loader() is now deprecated.
libxml 2.9.0 is required which guarantees entity loading and thereby protecting against XXE attacks.
PGSQL / PDO PGSQL
PGSQL_LIBPQ_VERSION_STR is deprecated.
Function aliases deprecate in PHP 8.
Standard Library
An implementation that returns an integer (<, =, > zero) replaces the sort comparison functions append with a deprecation warning.
Zip
ZipArchive is deprecated. Instead, a Null/empty file is applicable.
ZipArchiveis used instead of the procedural API of zipping as it is deprecated.
ZipArchive::statIndex() and a for loop is used for iteration overall entries.
Reflection
ReflectionParameter::getType() and the ReflectionType APIs can be used as ReflectionFunction::isDisabled(), ReflectionParameter::getClass(), ReflectionParameter::isArray(), ReflectionParameter::isCallable() are deprecated.
Challenges with PHP 8.0
Existing WordPress projects need to migrate to PHP 8.0. Well-types codebases run smoothly with upcoming versions of PHP. Everything else requires migration to avoid breakage.
There are issues with standard WordPress installation with PHP 8.
PHP 8 comes with many compatibility issues.
Create a backup before testing the new version of the WordPress website with PHP 8. Developers need to take a leap of faith and dive into PHP development with WordPress as it is better-off than previous versions.
Conclusive: Are we ready to embrace changes with PHP 8.0?
We learned that PHP 8.0 brings in major changes to – The JIT compiler; Attributes; Named arguments; Match expressions; Throw expressions (rfc) – Arrow functions, Coalesce Operators, Ternary Operators; Static return type(rfc); Union type(rfc) and Mixed types (rfc); and other interesting features like – Make Sorting Stable(rfc); Constructor Property Promotion(rfc); Zero Safe Operator(rfc); str_contains(rfc); Weak Maps(rfc); Non-capturing Catches(rfc);
Including a word of caution here, developers should consider updating after testing once a stable release is available every year with your WordPress Hosting Provider. PHP progresses naturally. And, before we explore the one at hand, a new version becomes available with updates. Decide the way you wish to proceed with the performance and growth of your business. We endure PHP development services within budget. Hire PHP developers on dedicated or outsourcing models.
YOU MAY ALSO LIKE
10 Top Websites like Etsy that Sell Handmade Products
Neeti Kotia is a technology journalist who seeks to analyze the advancements and developments in technology that affect our everyday lives. Her articles primarily focus upon the business, social, cultural, and entertainment side of the technology sector.
Oops, Something goes wrong please check your email address and verify captcha or please try again.
We have updated our Privacy Policy. You can accept it by clicking “I accept” button or you can continue to use our website without changing your browser settings.
Subscribe to our newsletter
Get updates on awesome happenings in the technology world!
Oops, Something goes wrong please check your email address and verify captcha or please try again.