Core\ObjectSet::clear
$objectSet->clear(): voidRemoves every value from a Core\ObjectSet. After clear, the count is 0 and isEmpty returns true. clear returns nothing.
The set itself is still there, so you can add values to it again. Every variable that points to the set sees the empty set.
clear frees the values the set kept alive. An object that nothing else uses is deleted at that point. Clearing a set that is already empty does nothing.
The examples show a set before and after clear, adding values again after clear, and a common use: one set that is emptied before each batch of work.
Return value
Returns void. Nothing. You can add values to the same set again.
Examples
Empty a set
<?nvs// Shows a set before and after `clear`.
final class Item{ public string $name;
public function constructor(string $name) { $this->name = $name; }}
Item $pen = new Item('pen');Item $cup = new Item('cup');
Core\ObjectSet<Item> $cart = new Core\ObjectSet<Item>();$cart->add($pen);$cart->add($cup);// This prints 2.echo $cart->count(), "\n";
$cart->clear();// The set is now empty. This prints 0, then "empty", then "no".echo $cart->count(), "\n";echo $cart->isEmpty() ? 'empty' : 'not empty', "\n";echo $cart->has($pen) ? 'yes' : 'no', "\n";20emptynoAdd again after clear
<?nvs// Shows that you can add values to a set again after `clear`.
Core\ObjectSet<int> $ids = new Core\ObjectSet<int>();$ids->add(10);$ids->add(20);$ids->clear();
$ids->add(30);$ids->add(10);
// Only the values added after `clear` are in the set. This prints "10: yes" and "20: no".echo '10: ', $ids->has(10) ? 'yes' : 'no', "\n";echo '20: ', $ids->has(20) ? 'yes' : 'no', "\n";
// A `foreach` gives the values in the order they were added after `clear`.// This prints 30, then 10.foreach ($ids as int $id) { echo $id, "\n";}10: yes20: no3010Reuse one set per batch
<?nvs// Shows how to use one set for many batches of work, and empty it before each batch.
final class Mail{ public string $to;
public function constructor(string $to) { $this->to = $to; }}
final class Sender{ public Core\ObjectSet<Mail> $sent;
public function constructor() { $this->sent = new Core\ObjectSet<Mail>(); }
// Sends each mail in the batch once, even if the batch lists it twice. public function send(array<Mail> $batch): uint { $this->sent->clear(); foreach ($batch as Mail $mail) { $this->sent->add($mail); } return $this->sent->count(); }}
Mail $a = new Mail('ana@example.com');Mail $b = new Mail('li@example.com');Mail $c = new Mail('sam@example.com');
array<Mail> $first = [$a, $b, $a];array<Mail> $second = [$c];
Sender $sender = new Sender();// `clear` empties the set before each batch. This prints 2, then 1.echo $sender->send($first), "\n";echo $sender->send($second), "\n";21