{"id":45,"date":"2024-09-27T14:07:52","date_gmt":"2024-09-27T14:07:52","guid":{"rendered":"https:\/\/blog.akbv.dev\/?p=45"},"modified":"2024-09-27T14:54:35","modified_gmt":"2024-09-27T14:54:35","slug":"php-8-new-features-and-improvements","status":"publish","type":"post","link":"https:\/\/blog.akbv.dev\/?p=45","title":{"rendered":"PHP 8: New Features and Improvements"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\" id=\"php-8--key-changes-and-features\">PHP 8: Key Changes and Features<\/h2>\n\n\n\n<p>If you stopped paying attention to PHP updates after 2012, you&#8217;d be forgiven for thinking that PHP is dead. However, PHP is alive and kicking, having undergone several vital improvements since 2012 with the introduction of PHP 5.4. Don&#8217;t believe it? Let&#8217;s look at some of the many language changes that PHP has undergone, right up to PHP 8.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"traits\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#traits\"><\/a>Traits:<\/h2>\n\n\n\n<p>PHP 5.4 brought an end to the monotonous rewriting of the same method body or abusing inheritance by introducing Traits, which favor composition over inheritance. In layman&#8217;s terms, Traits are chunks of code that you can use in different classes without having to duplicate the code or inherit classes.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"old-way\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#old-way\"><\/a>Old way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>class Foo{\n    public function log($msg){\n        <em>\/\/log message<\/em>\n    }\n}\n\nclass Bar{\n    public function log($msg){\n        <em>\/\/log message<\/em>\n    }\n}\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"new-way\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#new-way\"><\/a>New way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>trait Logger{\n    public function log($msg){\n        <em>\/\/log message<\/em>\n    }\n}\n\nclass Foo{\n    use Logger;\n}\n\nclass Bar{\n    use Logger;\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"short-array-syntax\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#short-array-syntax\"><\/a>Short Array Syntax:<\/h2>\n\n\n\n<p>In PHP 5.4, no more writing out &#8216;array&#8217; like a caveman; you can simply use square brackets for an array.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$names = array('Jeffrey', 'John', 'Mary');          <em>\/\/ Old way<\/em>\n$names = &#91;'Jeffrey', 'John', 'Mary'];               <em>\/\/ New way<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"array-destructuring\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#array-destructuring\"><\/a>Array Destructuring:<\/h2>\n\n\n\n<p>Instead of assigning an array to a temporary variable to define multiple variables, now, you can use array destructuring.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$array = array('a', 'b', 'c');\n$a = $names&#91;0];\n$b = $names&#91;1];\n$c = $names&#91;2];\n\n<em>\/\/ turns into this<\/em>\n$array = array('a', 'b', 'c');\n&#91;$a, $b, $c] = $names;\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"first-class-variadic-functions\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#first-class-variadic-functions\"><\/a>First-class Variadic Functions<\/h2>\n\n\n\n<p>With PHP 8, it&#8217;s possible to make use of first-class variadic functions, allowing you to pass as many arguments to a function as you might need, using the &#8216;&#8230;&#8217; operator.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function sum(...$numbers){\n    return array_sum($numbers);\n}\necho sum(1, 2, 3, 4); <em>\/\/ Outputs 10<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"arrow-functions\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#arrow-functions\"><\/a>Arrow Functions<\/h2>\n\n\n\n<p>Those familiar with JavaScript will feel at home with PHP 8&#8217;s introduction of arrow functions. These functions make use of the &#8216;fn&#8217; keyword to define a new function in a more compact and readable format.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"old-way-1\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#old-way-1\"><\/a>Old way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>array_map(function($item){\n    return $item-&gt;id;\n}, $items);\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"new-way-1\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#new-way-1\"><\/a>New way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>array_map(fn($item) =&gt; $item-&gt;id, $items);\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"null-coalescing-operator\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#null-coalescing-operator\"><\/a>Null Coalescing Operator<\/h2>\n\n\n\n<p>PHP 7 first gave us the null coalescing operator, allowing for more concise and readable code. This operator returns its first operand if it exists and is not null; otherwise, it returns its second operand.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$username = $_GET&#91;'user'] ?? 'nobody';\n<\/code><\/pre>\n\n\n\n<p>PHP 7.4 further improved this by bringing the null coalescing assignment operator &#8216;??=&#8217;. This operator will leave the variable as-is if it&#8217;s already set; otherwise, it will assign the given value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$_GET&#91;'user'] ??= 'nobody';\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"null-chaining-operator\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#null-chaining-operator\"><\/a>Null Chaining Operator<\/h2>\n\n\n\n<p>The null chaining operator introduced in PHP 8 has significant improvements in operating with objects and properties. It will stop the chain and return null if a null value is encountered.<\/p>\n\n\n\n<p>Old way:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$age = $user-&gt;age;\n$age = $age ? $age-&gt;format('Y-m-d') : null;\n<\/code><\/pre>\n\n\n\n<p>New way:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$age = $user-&gt;age?-&gt;format('Y-m-d');\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"named-arguments\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#named-arguments\"><\/a>Named Arguments<\/h2>\n\n\n\n<p>Named arguments give you the freedom to skip optional parameters without the need to insert a null value, keeping your function calls cleaner and more self-documented.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"old-way-2\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#old-way-2\"><\/a>Old way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>function createOrder($user, $product, $quantity = null, $price){\n    <em>\/\/create order<\/em>\n}\ncreateOrder($user, $product, null, 100);\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"new-way-2\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#new-way-2\"><\/a>New way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>function createOrder($user, $product, $quantity = null, $price){\n    <em>\/\/create order<\/em>\n}\ncreateOrder(\n    user: $user,\n    product: $product,\n    price: 100,\n);\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"weak-maps\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#weak-maps\"><\/a>Weak Maps<\/h2>\n\n\n\n<p>A new data structure was added to PHP 8 called Weak Maps for objects that will get garbage collected when there are no more references to that object. This is a fantastic memory-saving tool.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Foo{\n    protected WeakMap $cache;\n\n    public function get($key){\n        return $this-&gt;cache&#91;$key] ?? null;\n    }\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"enums\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#enums\"><\/a>Enums<\/h2>\n\n\n\n<p>Enums provide a way to define a set of named values with corresponding constants. PHP 8 introduces native enums, allowing you to define your own enumerated types with fewer chances of errors.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>enum Status: int\n{\n    case DRAFT = 1;\n    case PUBLISHED = 2;\n    case ARCHIVED = 3;\n\n    <em>\/\/friendly display<\/em>\n    public function display(): string\n    {\n        return match ($this) {\n            self::DRAFT =&gt; 'Draft',\n            self::PUBLISHED =&gt; 'Published',\n            self::ARCHIVED =&gt; 'Archived',\n        };\n    }\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"typed-properties\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#typed-properties\"><\/a>Typed Properties<\/h2>\n\n\n\n<p>With PHP 7.4 came the ability to specify types for class properties, ensuring better code quality and eliminating potential errors. PHP 8 builds upon this feature to provide more concise syntax and additional read-only properties.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"old-way-3\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#old-way-3\"><\/a>Old way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>class Foo{\n    public string $title;\n    public DateTime $date;\n\n    public function __construct(string $title, DateTime $date){\n        $this-&gt;title = $title;\n        $this-&gt;date = $date;\n    }\n}\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"new-way-3\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#new-way-3\"><\/a>New way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>class Foo{\n    public function __construct(\n        public string $title,\n        public readonly DateTime $date,\n    ){}\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"match-statement-switch\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#match-statement-switch\"><\/a>Match Statement (switch)<\/h2>\n\n\n\n<p>The match statement is an enhanced version of the switch statement, providing more expressive syntax and making switch statements cleaner and more readable.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"old-way-4\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#old-way-4\"><\/a>Old way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>switch($status){\n    case 200:\n        $message = 'OK';\n        break;\n    case 300:\n        $message = 'Multiple Choices';\n        break;\n    case 400:\n        $message = 'Bad Request';\n        break;\n    case 500:\n        $message = 'Internal Server Error';\n        break;\n}\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"new-way-4\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#new-way-4\"><\/a>New way:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>$message = match($status){\n    200 =&gt; 'OK',\n    300 =&gt; 'Multiple Choices',\n    400 =&gt; 'Bad Request',\n    500 =&gt; 'Internal Server Error',\n    default =&gt; 'Unknown Status',\n};\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"type-hints-and-type-declarations\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#type-hints-and-type-declarations\"><\/a>Type Hints and Type Declarations<\/h2>\n\n\n\n<p>Type hints and type declarations are a significant addition to PHP, enabling you to specify the expected parameter and return types for functions and methods. This enhances code clarity and offers better validation during development.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Foo{\n    public function setStatus(Status $status){\n        <em>\/\/<\/em>\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>PHP 7 and PHP 8 have made significant strides in terms of type safety, allowing developers to add type hints to function arguments, return values, and class properties. This helps catch potential type-related errors during development and improves code reliability.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"typed-arguments-and-return-types\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#typed-arguments-and-return-types\"><\/a>Typed Arguments and Return Types<\/h2>\n\n\n\n<p>In previous versions of PHP, function arguments and return types were not explicitly defined. However, PHP 7 introduced the ability to specify the expected types for function arguments and return values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function add(int $a, int $b): int {\n    return $a + $b;\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, the&nbsp;<code>add<\/code>&nbsp;function expects two integer arguments (<code>$a<\/code>&nbsp;and&nbsp;<code>$b<\/code>) and returns an integer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"union-types\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#union-types\"><\/a>Union Types<\/h2>\n\n\n\n<p>PHP 8 introduced union types, which allow you to specify that a parameter or return value can be of more than one type. This is useful when a variable can hold different types of values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function sum(int|float ...$numbers): int|float {\n    return array_sum($numbers);\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, the&nbsp;<code>sum<\/code>&nbsp;function can accept either&nbsp;<code>int<\/code>&nbsp;or&nbsp;<code>float<\/code>&nbsp;values as variable arguments and can return either an&nbsp;<code>int<\/code>&nbsp;or&nbsp;<code>float<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"intersection-types\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#intersection-types\"><\/a>Intersection Types<\/h2>\n\n\n\n<p>Intersection types, also introduced in PHP 8, allow you to specify that a parameter or return value must adhere to multiple types simultaneously. This is useful when you want to ensure that an object implements multiple interfaces, for example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function someMethod(Foo &amp; Bar $input): void {\n    <em>\/\/ Code here<\/em>\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, the&nbsp;<code>$input<\/code>&nbsp;parameter must be an object that implements both the&nbsp;<code>Foo<\/code>&nbsp;and&nbsp;<code>Bar<\/code>&nbsp;interfaces.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"nullable-types\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#nullable-types\"><\/a>Nullable Types<\/h2>\n\n\n\n<p>Nullable types allow you to specify that a parameter or return value can be either of a specified type or&nbsp;<code>null<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function setAge(?int $age): void {\n    <em>\/\/ Code here<\/em>\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, the&nbsp;<code>setAge<\/code>&nbsp;function expects an optional&nbsp;<code>int<\/code>&nbsp;parameter but also allows&nbsp;<code>null<\/code>&nbsp;values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"readonly-properties\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#readonly-properties\"><\/a>Read-only Properties<\/h2>\n\n\n\n<p>PHP 8 introduced a new&nbsp;<code>readonly<\/code>&nbsp;modifier for class properties, allowing you to specify that a property can only be initialized once and cannot be modified after that.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Foo {\n    public function __construct(public readonly string $name) {}\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, the\u00a0<code>name<\/code>\u00a0property is marked as\u00a0<code>read-only<\/code>, indicating that it can only be assigned a value during object construction but cannot be modified later.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"performance-improvements\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#performance-improvements\"><\/a>Performance Improvements<\/h2>\n\n\n\n<p>One common misconception is that PHP is slow. However, PHP has undergone significant performance improvements in recent years, making it capable of handling most use cases efficiently.<\/p>\n\n\n\n<p>Between PHP 5.6 and PHP 7, there was nearly a 400% performance increase, and PHP 8 brought additional performance enhancements, improving speed by about 20%.<\/p>\n\n\n\n<p>While PHP might not be suitable for extremely high-performance scenarios with tens of thousands of requests per second, it is fast enough for the majority of web development needs. For specialized use cases with high-performance requirements, there are other specialized languages available.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\"><a href=\"https:\/\/akbv.dev\/blog\/php8-new-features-and-updates#conclusion\"><\/a>Conclusion<\/h2>\n\n\n\n<p>PHP has evolved significantly since 2012, with the introduction of numerous features and improvements in PHP 5.4, PHP 7, and PHP 8. Traits, short array syntax, array destructuring, variadic functions, arrow functions, null coalescing operators, named arguments, and improved switch statements are just some of the many enhancements brought to the language. Additionally, PHP has seen improvements in type safety, allowing developers to create more reliable and robust code. With performance advancements, PHP is faster than ever before.<\/p>\n\n\n\n<p>Therefore, it is safe to say that PHP is not dead. It remains a popular and relevant programming language, constantly evolving to meet the demands of modern web development.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>PHP 8: Key Changes and Features If you stopped paying attention to PHP updates after&hellip;<\/p>\n","protected":false},"author":1,"featured_media":63,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[45,41],"tags":[17,3,43,37,44],"class_list":["post-45","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news","category-php","tag-development","tag-php","tag-php8","tag-web","tag-web-development"],"_links":{"self":[{"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/posts\/45"}],"collection":[{"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=45"}],"version-history":[{"count":1,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/posts\/45\/revisions"}],"predecessor-version":[{"id":46,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/posts\/45\/revisions\/46"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=\/wp\/v2\/media\/63"}],"wp:attachment":[{"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=45"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=45"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.akbv.dev\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=45"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}