Re: [RFC] Path to Saner Increment/Decrement operators

From: Date: Wed, 18 Jan 2023 20:09:06 +0000
Subject: Re: [RFC] Path to Saner Increment/Decrement operators
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-119333@lists.php.net to get a copy of this message
> Le 18 janv. 2023 à 19:33, Alex Wells <autaut03@gmail.com> a écrit : > > Classes and methods is the expected way of implementing standard library in an OO language. New > APIs (such as the new Random api) use OO instead of functions and it makes more sense to use OO in > this case too: there's likely a place for other methods too, like toBase(int $otherBase) etc. > It would also be possible to use overloaded operators if needed. Fortunately, PHP is not (yet) a language where every problem requires the use and manipulation of objects implementing a generalised and unified solution. I guess that the OO way of writing: ```php function next_alpha_id(): string { static $x = 'zz'; return ++$x; } function next_num_id(): int { static $x = 0; return ++$x; } $my_id = next_alpha_id(); $my_other_id = next_num_id(); ``` would resemble to the following, except that mixed should be replaced by the use of generics. For brevity, I left the mandatory interfaces as exercise to the reader. ```php class IdGenerator { protected mixed $current; public function __construct( protected readonly IdGeneratorType $type , protected readonly IdGeneratorDirection $direction , mixed $start ) { $this->current = $start; } public function next(): mixed { // implementation... } } enum IdGeneratorType { case alphabetic; case numeric; } enum IdGeneratorDirection { case positive; case negative; } final class StandardGlobalAlphabeticIdGenerator { private static IdGenerator $id_generator; public static function get(): IdGenerator { return self::$id_generator ?? new IdGenerator( type: IdGeneratorType::alphabetic , direction: IdGeneratorDirection::positive , start: 'aaa' ); } } final class StandardGlobalNumericIdGenerator { private static IdGenerator $id_generator; public static function get(): IdGenerator { return self::$id_generator ?? new IdGenerator( type: IdGeneratorType::numeric , direction: IdGeneratorDirection::positive , start: 1 ); } } $my_id = StandardGlobalAlphabeticIdGenerator::get()->next(); $my_other_id = StandardGlobalNumericIdGenerator::get()->next(); ``` —Claude

« previous php.internals (#119333) next »