Generics in PHP
PHP doesn’t have built-in support for generics, but we can simulate some aspects of generics using other language features. Here’s an equivalent implementation:
<?php
// As an example of a function that works with different types,
// slicesIndex takes an array of any type and an element of that
// type and returns the index of the first occurrence of
// v in s, or -1 if not present.
function slicesIndex($s, $v) {
foreach ($s as $i => $element) {
if ($element === $v) {
return $i;
}
}
return -1;
}
// As an example of a class that works with different types,
// List is a singly-linked list with values of any type.
class ListNode {
public $value;
public $next;
public function __construct($value) {
$this->value = $value;
$this->next = null;
}
}
class List {
private $head;
private $tail;
public function push($v) {
$newNode = new ListNode($v);
if ($this->tail === null) {
$this->head = $newNode;
$this->tail = $newNode;
} else {
$this->tail->next = $newNode;
$this->tail = $newNode;
}
}
public function allElements() {
$elems = [];
$current = $this->head;
while ($current !== null) {
$elems[] = $current->value;
$current = $current->next;
}
return $elems;
}
}
// Main function to demonstrate usage
function main() {
$s = ["foo", "bar", "zoo"];
// When using the slicesIndex function, we don't need to specify
// the type - PHP's dynamic typing handles this for us.
echo "index of zoo: " . slicesIndex($s, "zoo") . "\n";
$lst = new List();
$lst->push(10);
$lst->push(13);
$lst->push(23);
echo "list: " . implode(", ", $lst->allElements()) . "\n";
}
main();To run the program, save it as generics.php and use the PHP interpreter:
$ php generics.php
index of zoo: 2
list: 10, 13, 23In this PHP implementation:
We’ve created a
slicesIndexfunction that works with arrays of any type. PHP’s dynamic typing allows this function to work with different types without explicit type parameters.We’ve implemented the
Listclass as a singly-linked list that can hold values of any type. Again, PHP’s dynamic typing allows this without explicit type parameters.The
pushandallElementsmethods are implemented similarly to the original Go code.In the
mainfunction, we demonstrate the usage of both theslicesIndexfunction and theListclass.
While PHP doesn’t have built-in generics, its dynamic typing provides flexibility similar to what generics offer in statically-typed languages. However, this comes at the cost of losing compile-time type checking.