A constructor method is invoked when an object is created. You can use it to set things up, ensuring that essential properties are assigned values, essential methods are invoked and any necessary preliminary work is completed.

<?php

class ShopProduct
{    
    public $title;
    public $producerMainName;
    public $producerFirstName;    
    public $price = 0;    
    public function __construct( 
        $title,        
        $firstName,        
        $mainName,        
        $price    
    ) {        
        $this->title = $title;        
        $this->producerFirstName = $firstName;
        $this->producerMainName = $mainName;        
        $this->price = $price;    
        }

        public function getProducer()  
        {        
            return $this->producerFirstName . " ".$this->producerMainName;    
        }
    }

Once again, I gather functionality into the class, saving effort and duplication in the code that uses it. The __construct() method is invoked when an object is created using the new operator:

<?php
$product1 = new ShopProduct(
    "My Antonia", 
    "Willa",
    "Cather",
    5.99
);
A ShopProduct object is now easier to instantiate and safer to use. instantiation and setup are completed in a single statement. any code that uses a ShopProduct object can be reasonably sure that all its properties are initialized

predictability is an important aspect of object-oriented programming. You should design your classes so that users of objects can be sure of their features. One way you can make an object safe is to render predictable the types of data it holds in its properties. One might ensure that a $name property is always made up of character data, for example. But how can you achieve this if property data is passed in from outside the class? In the next section, I examine a mechanism you can use to enforce object types in method declarations.


This post is part of series:

1 - Object Oriented Programming Concept2 - Classes3 - Objects4 - Methods5 - Constructors6 - Arguments and Types7 - Static Methods and Properties8 - Constant Properties9 - Abstract Classes10 - Interfaces11 - Traits
PHP#PHPOOP#OOP

Comments (0)