New features in PHP 8

Conversion Work

Flextime

When you compute with integers, floating-point numbers are often generated. Wouldn't it be useful if the corresponding function could return an int or a float value as needed. In PHP 8, this is achieved with union types. You simply combine several possible data types with a pipe character (|). In the example shown in Listing 7, area() returns either an int or a float value.

Listing 7

Data Types with Pipe

class Rect {
  public int|float $x, $y, $w, $h;
  public function area(): int|float {
    return $this->w * $this->h;
  }
}

Another new data type is mixed. It stands for one of the data types array, bool, callable, int, float, null, object, resource, or string. The mixed data type always occurs if the type information is missing. For example, you can use mixed to indicate that you cannot or do not want to specify the type of a variable at the corresponding position.

The new WeakMap data structure works much like an array but uses objects as keys (Listing 8). Garbage Collection can also collect the used objects, so if the program destroys $a at some point further downstream (e.g., intentionally with unset($a);), PHP would automatically remove the corresponding $cache[$a] entry.

Listing 8

WeakMap

$cache = new WeakMap;
$a = new Address;
$cache[$a] = 123;

In Figure 1, var_dump() outputs WeakMap once; an address object acts as the key here. Then unset() destroys this object, which automatically removes the entry from WeakMap. This is proven by the second output of var_dump() (shown in the last two lines of Figure 1). One of WeakMap's main areas of application is customized caching.

Figure 1: The entry in WeakMap disappears along with the object.

More Functional

Whether or not the Hello World string contains the word World is determined by the strpos() function. In PHP 8, there is an alternative to this: str_contains() (Listing 9). The siblings str_starts_with() and str_ends_with(), which search for the word at the beginning and at the end of the string, respectively, are new. The fdiv() function divides a floating-point number by zero without grumbling and returns INF, -INF, or NAN.

Listing 9

str_contains()

if (str_contains('Hello World', 'World')) { [...] }

The get_debug_type() function determines the data type of a variable. In contrast to the already existing gettype(), the new function also identifies strings, arrays, and closed resources, and it reveals the classes of objects. As the function name suggests, it is mainly intended to make writing debug messages easier. Each resource, such as an open database connection, is assigned an internal identification number. Developers now can also address them in a type-agnostic way using get_resource_id().

The well-known token_get_all() function returns the matching PHP tokens for PHP source code [3]. You can have either a string or an array, which is anything but handy. This has led to PHP 8 introducing the PhpToken class. Its getAll() method returns an array of PhpToken objects, which in turn encapsulate the individual tokens. This token_get_all() replacement is easier to use, but at the price of using more memory.

Attributes

Many other languages offer annotations to let programmers attach metadata to classes. In this way, the developers can make a note of, say, the database table in which the class stores its data. PHP 8 now has an option for this in the form of attributes. The actual information is located between #[ ... ] directly in front of the class, as shown in Listing 10.

Listing 10

Attributes

#[DatabaseTable("User")]
class User
{
  #[DatabaseColumn]
  public $name;
  public function setBirthday(#[ExampleAttribute] $bday) { }
}

As the example demonstrates, attributes can be attached to classes, but also to variables, constants, methods, functions, and parameters. The information's structure and content is determined by the developer or a framework that evaluates the attributes. In Listing 10, the class is assigned an attribute of DatabaseTable. If necessary, you can pass in parameters in the brackets. The example reveals that the database table is named User.

The PHP developers have been working on the syntax for attributes for quite some time. There was some talk of using <<ExampleAttribute>> and @@ExampleAttributes as tags, and you will find references to this in numerous posts on PHP 8.

Attributes can be read using the Reflection API. The example shown in Listing 11 uses the new getAttributes() method to get all the attributes for the User class in the form of an array with all attributes. Each one encapsulates an object of the type ReflectionAttributes. Among other things, this new class has a getName() method that reveals the name of the attribute.

Listing 11

Reading Attributes

01 $reflectionClass = new \ReflectionClass(User::class);
02 $attributes = $reflectionClass->getAttributes();
03 var_dump($attributes[0]->getName());
04 var_dump($attributes[0]->getArguments());

The getName() method is used in line 3 of Listing 11, which simply outputs the name of the attribute via var_dump() – in the DatabaseTable example. Similarly, getArguments() in line 4 returns the corresponding parameters as an array (Figure 2).

Figure 2: For the #[DatabaseTable("User")] attribute, the Reflection API correctly returns DatabaseTable as the name and User as the parameter. All parameters are bundled into an array.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Pandas: Data analysis with Python
    The Python Data Analysis Library, or Pandas, is built on top of the fast math library NumPy and makes analysis of large volumes of data an easy and efficient experience.
  • Modern Fortran – Part 2

    Fortran 90 was only the start. The next two iterations – 95 and 2003 – pulled Fortran into a new era of programming languages.

  • Data Analysis with Panda

    The Python Data Analysis Library, or Pandas, is built on top of the fast math library NumPy and makes analysis of large volumes of data an easy and efficient experience.

  • Innovations in PowerShell 5
    Windows 10 brings an updated, fifth release of PowerShell that vastly simplifies the task of managing modules and software packages. The scripting language now also handles various formatted output from commands and selection lists.
  • CoffeeScript: A Replacement for JavaScript?

    Through the years, many languages have tried to improve or even replace JavaScript, including CoffeeScript, which runs in all JavaScript Runtime Environments and compiles into JavaScript.

comments powered by Disqus
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs



Support Our Work

ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.

Learn More”>
	</a>

<hr>		    
			</div>
		    		</div>

		<div class=