What is the DS\Set __construct() method in PHP?

The __construct() method of PHP’s DS\Set class uses a traversable object or array of values to create a new instance of a DS\Set object.

The process is illustrated below.

Syntax

The prototype of the __construct() method is shown below.

public Ds\Set::__construct(mixed $values = [])

Parameters

The __construct() method accepts a single parameter, i.e., a traversable object or an array of values, to initialize the instance. The provided values may have any data type.

Return value

The __construct() method returns the newly created DS\Set instance.

Example

The code below shows how the __construct() method works in PHP.

<?php
// create sets
$setOne = new \DS\Set();
$setTwo = new \Ds\Set([5, 10, 15]);
$setThree = new \Ds\Set([1, "abc", 10, 2, "efg"]);
// print sets
print_r($setOne);
print_r($setTwo);
print_r($setThree);
?>

Output

The code above produces the following output.

Ds\Set Object
(
)
Ds\Set Object
(
[0] => 5
[1] => 10
[2] => 15
)
Ds\Set Object
(
[0] => 1
[1] => abc
[2] => 10
[3] => 2
[4] => efg
)

Note: To run this program, you need to install Data Structures for PHP on your local machine.

Explanation

The __construct() method is implicitly invoked whenever the new keyword is used to initialize a set instance.

The code above creates three unique set instances in lines 4 to 6. Each instance is initialized through the new keyword which invokes the __construct() method.

setOne is created as an empty set, setTwo contains three integer values, and setThree contains a mix of strings and integers. Each set is printed accordingly.

Free Resources