PHP - Constructor with default arguments

Introduction

A constructor can use default arguments.

The following code adds a default argument to Book

class Book { 
    public function __construct( 
        int $isbn, 
        string $title, 
        string $author, 
        int $available = 0 
     ) { 
        $this->isbn = $isbn; 
        $this->title = $title; 
        $this->author = $author; 
        $this->available = $available; 
     } 

We could use the preceding constructor in two different ways:

$book1 = new Book("2018", "C", 0003, 12); 
$book2 = new Book("2018", "C", 0003); 

$book1 will set the number of units available to 12, whereas $book2 will set it to the default value of 0. But do not trust me; try it by yourself!

Related Topic