Adding methods
Add add, remove and find methods to the class.
Adding methods to the collection
Methods make the class do work. You'll add three core methods to the Collection class: add appends a new item, remove deletes one, and find returns an item's position.
Each method reaches the internal array through $this. You use $this->items[] = $item; to add, array_search to find, and unset to remove. These are array functions you learned in earlier lessons.
Method chaining
When a method does return $this;, the returned value is the same instance. So you can call methods one after another: $c->add("pear")->add("cherry");.
This is called chaining. By writing return $this; in add and remove you gain a fluent API. find returns a position, so it isn't used for chaining.
Exercise Add add, remove and find methods
Add three methods to the Collection class. add(string $item): $this->items[] = $item; then return $this;. remove(string $item): find with array_search, delete with unset, return $this;. find(string $item): find with array_search; if false return null, else return the position. Then start with $c = new Collection(["apple"]);, chain $c->add("pear")->add("cherry");, remove with $c->remove("apple"); and print the count with echo count($c->items);.
Show example solution
$this->items[] = $item; return $this;. remove: find with array_search, delete with unset, return $this;. find: find with array_search, return null if false else the position. Start with new Collection(["apple"]), chain $c->add("pear")->add("cherry");, remove with $c->remove("apple");.
Example solution:
<?php
// Collection class skeleton
class Collection {
public array $items = [];
public function __construct(array $initial = []) {
$this->items = $initial;
}
public function add(string $item) {
$this->items[] = $item;
return $this;
}
public function remove(string $item) {
$key = array_search($item, $this->items, true);
if ($key !== false) {
unset($this->items[$key]);
}
return $this;
}
public function find(string $item) {
$key = array_search($item, $this->items, true);
return $key === false ? null : $key;
}
}
$c = new Collection(["apple"]);
$c->add("pear")->add("cherry");
$c->remove("apple");
echo count($c->items);
Test yourself
-
What does method chaining require?
- Methods to be declared static
- Methods to return $this
- The class to be inherited
- Properties to be public
Show answer
Methods to return $this — Correct. When a method returns $this, the next method can be called directly on it: $c->add("x")->add("y").
-
Make add return $this
public function add(string $item) { $this->items[] = $item; return ____ }Show answer
public function add(string $item) { $this->items[] = $item; return $this; } -
Match the method and chaining concepts
- return $this;
- Enables chaining
- $this->items[]
- Append to array
- array_search
- Find an item
- unset
- Remove an item