php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #65162 Add Generics support
Submitted: 2013-06-28 18:17 UTC Modified: 2021-07-02 19:00 UTC
Votes:58
Avg. Score:4.6 ± 0.8
Reproduced:39 of 39 (100.0%)
Same Version:27 (69.2%)
Same OS:27 (69.2%)
From: matutetandil at gmail dot com Assigned:
Status: Suspended Package: Class/Object related
PHP Version: Irrelevant OS: Any
Private report: No CVE-ID: None
 [2013-06-28 18:17 UTC] matutetandil at gmail dot com
Description:
------------
Add generics support to PHP. So you can declare classes like this:

class MyGenericClass<T> {
   private $object;

   public function __construct() {
       $this->object = new T();
   }
}

or

class MyGenericClass<T extends SuperTClass> {
   private $object;

   public function __construct() {
       $this->object = new T();
   }
}

In the first case you can make a new (supposing that there is defined a B 
class):
$a = new MyGenericClass<B>();

and in the second example you are forcing B to be a SuperTClass.

I hope you can implement this feature! Is great!!!

Expected result:
----------------
Generics included in a PHP relase.

Actual result:
--------------
No Generics support.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-06-21 20:15 UTC] cmb@php.net
FWIW, there is a respective RFC in draft status:
<https://wiki.php.net/rfc/generics>.
 [2016-09-07 18:32 UTC] php at mattjanssen dot com
There is a $1,000 bounty on this request: <https://www.bountysource.com/issues/20553561-add-generics-support>.
 [2021-07-02 08:39 UTC] fcolecumberri at hotmail dot com
smething like this??:

<?php

class MyClassA {}
class MyClassB {}
class MyClassC {}


class MyGenericClass {
   public $object;

   public function __construct($T) {
       $this->object = new $T();
   }
}

$mgc_a = new MyGenericClass(MyClassA::class);
$mgc_b = new MyGenericClass(MyClassB::class);
$mgc_c = new MyGenericClass(MyClassC::class);

echo get_class($mgc_a->object)."\n";
echo get_class($mgc_b->object)."\n";
echo get_class($mgc_c->object)."\n";
 [2021-07-02 17:51 UTC] requinix@php.net
-Status: Open +Status: Suspended
 [2021-07-02 19:00 UTC] matutetandil at gmail dot com
The implementation os Generics, is more than just creating a new class inside another class by passing the type by parameter.

The main idea behind this, is to allow the class to only receive parameters of certain type defined when the class is created. this way, you can have for instance an Generic Array, that only accepts Strings and another Generic Array that only allows integer values.

You can read more about this here: https://en.wikipedia.org/wiki/Generic_programming
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 14:01:32 2024 UTC