PHP - Custom Type Class methods

Introduction

Class methods are functions defined inside a class.

Like functions, methods can have arguments and perform some actions, optionally returning a value.

Methods inside class can use the properties of the object that invoked them.

Calling the same method in two different objects might have two different results.

Demo

<?php 
     class Book { 
        public $isbn; 
        public $title; 
        public $author; 
        public $available; 

        public function getPrintableTitle(): string { 
            $result = $this->title . '\n' . $this->author; 
            if (!$this->available) { 
                $result .= 'Not available'; 
            } //from w ww.  jav a  2 s  . c o  m
            return $result; 
        } 

        public function getCopy(): bool { 
            if ($this->available < 1) { 
                return false; 
            } else { 
                $this->available--; 
                return true; 
            } 
         } 
     }

     $book = new Book(); 
     $book->title = "2018"; 
     $book->author = "C"; 
     $book->isbn = 0003; 
     $book->available = 12; 

     if ($book->getCopy()) { 
        echo 'Here, your copy.'; 
     } else { 
        echo 'I am afraid that book is not available.'; 
     } 
?>

Result

Related Topics