This article describes the sample code of the PHP builder mode. For more information, see
PHP builder code example
Size = $ size;} public function setColor ($ color) {$ this-> color = $ color;} public function setType ($ type) {$ this-> type = $ type;} public function toString () {ob_start (); echo 'Size: ', $ this-> Size ,'
'; Echo 'color:', $ this-> Color ,'
'; Echo 'type:', $ this-> Type ,'
'; Return ob_get_clean () ;}// calling each method is not the best practice. $ product = new Product (); $ product-> setSize (100 ); $ product-> setColor ('red'); $ product-> setType ('shirt'); // echo $ product; // -----------------------------------------------------------/*** builder mode * separates the construction of a complex object from its representation, make the same build process create different representations */class ProductBuilder {private $ product; private $ configs; public function construct ($ cfgs) {$ this-> configs = $ cfgs; $ this-> product = new Product ();}/*** build object */public function buildProduct () {$ this-> product-> setSize ($ this-> configs ['size']); $ this-> product-> setColor ($ this-> configs ['color']); $ this-> product-> setType ($ this-> configs ['type']);} public function getProduct () {return $ this-> product ;}} $ cfgs = array ('size' => 100, 'color' => 'blue', 'type' => 'shirt '); $ builder = new ProductBuilder ($ cfgs); $ builder-> buildProduct (); echo $ builder-> getProduct ();
The above is a detailed explanation of the PHP builder code example. For more information, see other related articles in the first PHP community!