Bifalgorithm post · Computer science one · Constructors

How does a constructor initialize a PHP object?

How does a constructor initialize a PHP object? (Computer science one · Constructors) — "If we make the (good) design decision to make our class immutable, we…

Ideas in this flowchart

  • An immutable class still needs a constructor to initialize its values.
  • A constructor is a special method that specifies how an object is constructed.
  • Built-in types are interpreted and assigned by PHP automatically.
  • User-defined objects such as Student require explicit construction rules.
  • PHP does not support function overloading inside classes.
  • A class can therefore have only one constructor.
  • PHP reserves the name __construct for the constructor method.
  • The two underscores identify a reserved magic method with a special purpose.
  • Magic methods must be declared public.
  • If no constructor is defined, PHP creates an object whose member variables have null values.
  • The example constructor lets a user specify firstName, lastName, id, and gpa.
  • The constructor assigns each parameter to the corresponding Student member variable.
Feed/

How does a constructor initialize a PHP object?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.