PHP

  minte9
REMEMBERS




Last update:   12-04-2022

Typed

PHP 7.4 finally brings typed properties.
 
declare(strict_types=1);

/**
 * Prior to PHP 7.4
 * 
 * This sort of strict data would have required ...
 * to enforce the data integrity.
 * 
 *      setBirthDate(DateTime $birthday): void
 *      getBirthDate(): \DateTime 
 * 
 * Unititalized state:
 * 
 * To mark a property can be null, prefix its type with a question mark.
 * Even if a property is nullable, its uninitialized value will not be null.
 */

class A 
{
    public ?String $name; // can be null
    public DateTime $birthday;  // Look Here

    public function setBirthDay($day) 
    {
        $this->birthday = $day;
    }

    public function getBirthDay()
    {
        return $this->birthday->format('d-m-Y');
    }
}

$a = new A();
$a->name = null; // set as null
$a->setBirthDay(new DateTime('2011-12-01'));
echo $a->getBirthDay(); // 01-12-2011

try {
    $a = new A();
    $a->name = 10;
} catch(TypeError $e) {
    echo $e->getMessage(); // Cannot assign int to property
}

Arrow

Arrow functions are a way of writing shorter functions.
 
/**
 * Arrow functions, also called "short closures", 
 * allow for less verbose one-liner functions.
 */

$posts = [
    (object) ['id' => 1, 'name' => 'John'],
    (object) ['id' => 2, 'name' => 'Mark'],
];

// PHP 7.4+
$ids = array_map(fn($post) => $post->id, $posts); // Look Here
print_r($ids); // [1, 2]

// PHP < 7.4 
$ids = array_map(function ($post) {
    return $post->id;
}, $posts);
print_r($ids); // [1, 2]

Questions     github Versions
Php8.0
        A B C D E F
🔔
1/2