Home > OS >  Programme Returns NULL Object
Programme Returns NULL Object

Time:12-10

I want to demonstrate Factory Design Pattern using PHP Code snippet. So i develop this code by my self. But it gives me NULL object .Please help me to resolve this .

<?php
class Book{
    private $bookName;
    private $bookAuthor;
    const lineBreak = "<br/>";

    public function __construct($bookName,$bookAuthor)
    {
        $this->bookName = $bookName;
        $this->bookAuthor = $bookAuthor;
    }

    public function getBookInfo(){
        return $this->bookName .'-'.$this->bookAuthor .self::lineBreak;
    }

    }

class BookFactory{

    public function __construct($bookName,$bookAuthor)
    {

        $book = new Book($bookName,$bookAuthor);

        return  $book->getBookInfo();

    }

}

$bookOne = new BookFactory("Digital World","David Perera");

$bookTwo = new BookFactory("Harry Porter","James bond");

var_dump($bookOne);

CodePudding user response:

You can't implement the factory pattern in the constructor. new Classname always returns an object of that class, not what the constructor returns.

Instead, you should use a static method to create the object.

class BookFactory{

    public static function createBook($bookName,$bookAuthor)
    {
        return new Book($bookName,$bookAuthor);
    }
}

$bookOne = BookFactory::createBook("Digital World","David Perera");
$bookTwo = BookFactory::createBook("Harry Porter","James bond");

var_dump($bookOne);

CodePudding user response:

Nothing can be done with the return value of a constructor (aside from using the Object it created).

You have two ways:

  1. Use "Object Inheritance"
class BookFactory extends Book {

    // Your content

}
  1. Use the Book class
  • Related