程序 Returns NULL 对象

Programme Returns NULL Object

我想使用 PHP 代码片段演示工厂设计模式。所以我自己开发了这段代码。但它给了我 NULL 对象。请帮我解决这个问题。

<?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);

不能在构造函数中实现工厂模式。 new Classname总是returns那个class的一个对象,而不是什么构造函数returns.

相反,您应该使用静态方法来创建对象。

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);