PHP code example of xiyusullos / nullable

1. Go to this page and download the library: Download xiyusullos/nullable 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/ */

    

xiyusullos / nullable example snippets




use xiyusullos\Nullable;

class Obj
{
    use Nullable;
    
    // ...
}

$obj = new Obj();
echo $obj->a->b->c;



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use xiyusullos\Nullable;

class Profile extends Model
{
    // supposed an attribute of departmentName
    use Nullable;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // ...
}

class User extends Model
{
    use Nullable;

    public function profile()
    {
        return $this->hasOne(Profile::class);
    }

    // ...
 }

class Blog extends Model
{
    use Nullable;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // ...
}

// wanna get the writer's department name who posted the blog #1

// without Nullable
$blog = Blog::find(1);
$user = $blog->user;
if ($user) {
    $profile = $user->profile;
    if ($profile) {
        $departmentName = (string) $profile->departmentName;
    }
} // that's so annoying!

// with Nullable
$blog = Blog::find(1);
$departmentName = (string) $blog->user->profile->departmentName;