Notes From PHP 7.4

Class Property Strict Type
class Person {
   public int $id;
   public string $name;
   public ?Foo $foo;
}

if we set $this->id = "4" then it will automatically cast in integer, but $this->id = "four" will return error.

Note: ? means nullable and we can only use null as a default if the type is nullable.

Serialization and Unserialization
class Person 
{
   public int $id;
   public string $name;

   public function __construct(int $id, string $name) {
   	  $this->id = $id;
   	  $this->name = $name;
   }

   public function __serialize() { // getter
      return ['id' => $this->id, 'name' => $this->name];
   }

   public function __unserialize(array $data) { //setter
      $this->id = $data['id'];
      $this->name = $data['name'];
   }
}
Arrow Function

Yes, they now have an arrow function

$people = [
    new Person(id: 1, name: 'anu'),
    new Person(id: 2, name: 'budu'),
    new Person(id: 3, name: 'danu'),
];

$skip = 2;

return array_map(function($data) use ($skip) {
   return $person->id + $skip;
}, $people);

// now with PHP 7.4 Array Function
return array_map(fn($person) => $person->id + $skip, $people);
Spread Operator

Bye bye array_merge()

$parts = ['jaguar', 'lion'];
$animals = [...$parts, 'tiger', 'leopard'];
Numeric Literal Seperator
$money = 10_000_000_000;
echo $money;
// output: 10000000000
Preload

The last thing yet still useful is preload. With this feature we did not have to use the Composer autoloader anymore, especially for framework. Since all of the framework code was preloaded, autoloading is unnecessary. To setup the preload files, we need to write a custom PHP script and link it to our php.ini file using opcache.preload. That script will executed once server start, all preloaded files are available in memory for all requests. But remember, changes made to preloaded files won't have any effect, until the server is restarted. For example, we add this to our php.ini:

opcache.preload=/path/to/project/preload.php

Where our preload.php will be:

$files = /* An array of files you want to preload */;

foreach ($files as $file) {
    opcache_compile_file($file);
}