PHP code example of 1tomany / nullify

1. Go to this page and download the library: Download 1tomany/nullify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

1tomany / nullify example snippets


nullify(string|\Stringable|null $string, bool $trim = true): ?string;

final readonly class Person
{
    public function __construct(
        private ?string $name,
    ) {
    }

    public function getName(): ?string
    {
        return $this->name;
    }
}

$person = new Person('     ');

if (null === $person->getName() || '' === trim($person->getName())) {
    throw new \InvalidArgumentException('Please enter a name.');
}

final readonly class Person
{
    /**
     * @var ?non-empty-string
     */
    private ?string $name;

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

    /**
     * @return ?non-empty-string
     */
    public function getName(): ?string
    {
        return $this->name;
    }
}

$person = new Person('     ');

if (null === $person->getName()) {
    throw new \InvalidArgumentException('Please enter a name.');
}

if (!$person->getName()) {
}

if (empty($person->getName())) {
}