Concept

How does a constructor initialize a PHP object?

ComputerScienceOne / Constructors

"If we make the (good) design decision to make our class immutable, we still need a way to initialize the values. This is where a constructor comes in. A constructor is a special method that specifies how an object is constructed. With built-in variable types such as an numbers or strings, PHP “knows” how to interpret and assign a value. However, with user-defined objects such as our Student class, we need to specify how the object is created. Just as with functions outside of classes, PHP does not support function overloading inside classes. That is, you can have one and only one function with a given identifier (name). Thus, there is only one possible constructor. Moreover, PHP reserves the name __construct for the constructor method. The two underscores are a naming convention used by PHP to denote “magic methods” that are reserved and have a special purpose in the language. Further, magic methods must be made public . Some magic methods provide default behavior while others do not. For example, if you do not define a constructor method, the default behavior will be to create an object whose member variables all have null values. The following constructor allows a user to construct an instance of our Student instance and specify all four member variables.\n\n1 public function __construct($firstName, $lastName, $id, $gpa) {\n\n2 $this->firstName = $firstName;\n\n3 $this->lastName = $lastName;\n\n4 $this->id = $id;\n\n5 $this->gpa = $gpa;\n\n571"

Related Ideas

How does a constructor initialize a PHP object? | ComputerScienceOne | Bifalgorithm | Bifalgorithm