PHP RFC: Generic Types and Functions best php traiing trivandrum

PHP RFC: Generic Types and Functions


Introduction

Proposal

Generic Types

class Entry<KeyType, ValueType>
{
    protected $key;
    protected $value;
 
    public function __construct(KeyType $key, ValueType $value)
    {
        $this->key   = $key;
        $this->value = $value;
    }
 
    public function getKey(): KeyType
    {
        return $this->key;
    }
 
    public function getValue(): ValueType
    {
        return $this->value;
    }
}
$entry = new Entry<int,string>(1, 'test');
$entry = new Entry(1, 'test');
var_dump(get_class($entry)); // => (string) "Entry"

Extending a Generic Type

Type-hinting and Type-checking Generic Types

Nested Type Arguments

Upper Bounds

interface Boxable
{
    // ...
}
 
class Box<T is Boxable>
{
    // ...
}
 
class Hat implements Boxable
{
    // ...
}
 
$box = new Box<Hat>(); // ok
$box = new Box<string>(); // throws a 
Note that the choice of the keyword is to indicate upper bounds is based on the rejection of perhaps more obvious alternatives - repurposing the extends or implements keywords would be misleading, since they would work precisely the same way; worse, permitting both keywords would render consumer code invalid if an upper bound type provided by a library is refactored between class and interface. Repurposing instanceof would also be misleading, since the upper bound is checking the type-hint, not an instance. Furthermore, we don't want this to collide with possible future mixed scalar types, such as number or scalar, neither of which make sense in conjunction with either extends or implements. (If a reserved is keyword is undesirable for other reasons, a simple : is likely a better alternative than overloading the meaning of an existing keyword.)
Bounds Checking

Traits

Generic Functions and Methods

Generic Methods

Generic Constructors

Generic Closures

Type Checking

Bounded Polymorphism

Multiple Constraints

Autoloading

Reflection

Reification

Static Type-checking With ''instanceof''
New Pseudo-types

Backward Incompatible Changes

Proposed PHP Version(s)

Proposed Voting Choices

Patches and Tests

References

Comments

Popular posts from this blog

A Tailwind CSS Preset for Laravel 5.5

Short and safe array iteration

PHPStorm's performance