PHP 8 Features, Challenges, Trends in 2021

blog_img
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!

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.

Technology Stack: Used by Major Companies

Facebook Technology Stack

  • PHP, ReactJS, Cassandra, Graphql, Hive
  • DevOps: Jenkins, Datadog, Chef

Hootsuite Technology Stack

  • PHP, JQuery, Bootstrap, MySQL, AWS, MongoDB, Kafka, Scala
  • DevOps: Jenkins, Docker, Github

9Gag Technology Stack

  • PHP, Laravel, VueJS, JavaScript, NgINX, Scala, AWS S3, Python, Scala, Java
  • DevOps: GitHub, Datadog, Docker

Backwards Compatibility: Feature Support

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

DifferencesDescriptionPHP 7PHP 8
Named ArgumentsArguments, parameters are order-dependent, self-documented. named arguments named arguments
AttributesWe can now use structured metadata with PHP’s native syntax instead of PHPDoc annotations. attributes attributes
Constructor PropertyLess repetitive code sections to define and initialize properties. constructor property constructor property
Union TypesUse of Native union type declarations instead of PHPDoc annotations for a combination of types validated at runtime. union types union types
Match ExpressionThe 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.

 match expression match expression
Nullsafe operatorInstead 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. nullsafe operator }

}

$country = $session?->user?->getAddress()?->country;
String to number comparisonsPHP 8 uses a number comparison, while comparing to a numeric string.0 ==’foobar’ // true 0 ==’foobar’ // false
Consistent type errors for internal functionsThe internal functions throw an Error exception in case the validation of the parameters fails. consistent type errors consistent type errors

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)

other feature

  • Static (Late state binding) is now used as a return type

other feature

  • 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.

other feature

  • The parameter list allows commas.

other feature

  • 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.

other feature

  • 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

internationalization-functions

  • LDAP

It now has ldap_count_references().

  • OPcache

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

reflection

  • SQLite3

SQLite3::setAuthorizer() and respective class constants are added to userland callback.

  • Standard Library

Following methods come along with some changes:

standard librarystandard library</>

  • 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)

zip

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.
  • odbc_connect() does not reuse connections.

OpenSSL

Regular Expressions (Perl-Compatible)

  • 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 

reflection

  • PHP 7 and PHP 8 codes make use of these signatures:

reflection

  • 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.
  • ReflectionNamedType replaces ReflectionType::isBuiltin() method.

Sockets 

  • 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:

standard php library

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.

standard php library

  • 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.
  • Standalone namespace separators use: T_NS_SEPARATOR

XMLReader

  • XMLReader::open() and XMLReader::xml() are instance and inheriting classes need to declare these as static if they override methods.

XML-RPC

  • XML-RPC extension is now part of PECL.

Zip

  • ZipArchive::OPSYS_CPM replaces ZipArchive::OPSYS_Z_CPM

Zlib

  • gzgetss() no longer exists.
  • output_compression is disabled for Content-Type: image/*.

Windows PHP Test Packs

  • run-test.php is now known as run-tests.php.

PHP Core

  • PHP 8 drops the default value as the required parameter follows it. The functionality remains intact.

php core

  • It comes with an exception: Type $param = null (null default makes the type implicitly nullable), the explicit nullable type is preferable.

php core

  • get_defined_functions() does not include disabled functions.
  • get_defined_functions() with exclude_disabled, set to false, is deprecated.

Enchant

  • ENCHANT_MYSPELL and ENCHANT_ISPELL is deprecated.
  • enchant_broker_set_dict_path(),enchant_broker_get_dict_path() – as this functionality is not available in libenchant < 1.5 or in libenchant-2.
  • enchant_dict_add() replaces enchant_dict_add_to_personal()
  • enchant_dict_is_added() replaces enchant_dict_is_in_session()
  • 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.

pgsql

Standard Library

  • An implementation that returns an integer (<, =, > zero) replaces the sort comparison functions append with a deprecation warning.

standard php library

Zip

  • ZipArchive is deprecated. Instead, a Null/empty file is applicable.
  • ZipArchive is used instead of the procedural API of zipping as it is deprecated.
  • ZipArchive::statIndex() and a for loop is used for iteration overall entries.

zip

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
About Author
Neeti Kotia

Neeti Kotia

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.

MAKE YOUR IDEA REACH ITS GRAND DESTINY

WITH PRO WEB AND MOBILE SOLUTIONS

Looking for a development partner?

Portfolio

Visit Our Portfolio

Top Mobile Blog Winner

Top 15 Latest Mobile Blogs

Mobile App Blog Winner

Mobile App Blogs

SUBSCRIBE TO OUR BLOG

Top

Get a perfect quote

We’re eager to work with you. Please share your project goals and contact information. We respond to 97% of messages within 1-2 business day. Really!

Or send us an email at: [email protected]