Best practices for static constructors

后端 未结 8 2452
无人及你
无人及你 2020-12-13 14:41

I want to create an instance of a class and call a method on that instance, in a single line of code.

PHP won\'t allow calling a method on a regular constructor:

8条回答
  •  爱一瞬间的悲伤
    2020-12-13 15:01

    These are called creation methods, and I typically name them createXXX() such as createById() or createEmptyCatalog(). Not only do they provide a nice way to reveal the different intentions of an object's constructors, but they enable immediate method chaining in a fluent interface.

    echo Html_Img::createStatic('/images/missing-image.jpg')
            ->setSize(60, 90)
            ->setTitle('No image for this article')
            ->setClass('article-thumbnail');
    

提交回复
热议问题