PHP
Class skeleton
Define a collection class and set up internal state with the constructor.
Setting up internal state with the constructor
When you create a collection, you often want to supply initial data. The __construct method runs automatically when an instance is created with new, and sets up the internal state of the class.
For the Collection class, the constructor takes an array parameter and assigns it to the $this->items property. So new Collection(["apple", "pear"]) starts the collection with two items.
Initializing a property with $this
Inside the constructor, the $this pseudo-variable points to the instance being created. To assign the parameter to the property you write $this->items = $initial;.
It's good practice to give the parameter a default value: array $initial = []. Then both new Collection() (empty) and new Collection(["apple"]) (filled) work.
Exercise Add the constructor
Add a public function __construct(array $initial = []) constructor to the Collection class. Inside it, assign the parameter to the property with $this->items = $initial;. Then create an instance with two items via $c = new Collection(["apple", "pear"]); and print the count with echo count($c->items);.
Show example solution
Add public function __construct(array $initial = []) { $this->items = $initial; } inside the class. Create an instance with new Collection(["apple", "pear"]) and print with echo count($c->items);.
Example solution:
<?php
// Collection class skeleton
class Collection {
public array $items = [];
public function __construct(array $initial = []) {
$this->items = $initial;
}
}
$c = new Collection(["apple", "pear"]);
echo count($c->items);
Test yourself
-
When does the constructor run?
- When the class is defined
- Automatically when the script starts
- When an instance is created with new
- When a method is called
Show answer
When an instance is created with new — Correct. __construct runs automatically when an instance is created with new.
-
Add a parameter to the constructor
public function __construct(array ____) {
$this->items = $initial;
}
Show answer
public function __construct(array $initial = []) {
$this->items = $initial;
}
-
Match the constructor concepts
- __construct
- Constructor name
- $this->items
- Property assignment
- new Collection()
- Instantiation
- array $initial
- Parameter type
Next lesson: Adding methods