-
-
Save auroraeosrose/df3976dfdd95e81a4cef to your computer and use it in GitHub Desktop.
<?php | |
use Eos\Datastructures\Immutable; | |
use Eos\Datastructures\Struct; | |
class Rectangle extends Struct implements Immutable { | |
public $x; | |
public $y; | |
public $height; | |
public $width; | |
} | |
$rect = new Rectangle(['x' => 5, 'y' => 6, 'height' => 56, 'width' => 19]); | |
$rect->x = 5; // will throw ImmutableException |
I can't muck with syntax in an extension (yet) sadly - so version 1.0 will not be able to have syntatic sugar
just overloading objects to give you struct functionality
Depending on uptake on this we'll see about doing a core patch
As for typing - yes being able to type properties would be fabulous but that is not currently in 7.0 yet (it's on the shortlist for 7.1, 7.2 inclusion)
Until then typing will be done either with
- a second array passed into the constructor with type definitions
- a "magic" __types property with type definitions
Yes this is ugly - but until we get the RFC and patch in for nullable typehints and property typehints there's no other way to get it done
I'll add a ->with to the immutable version of the struct, and also do a "strictobject" which is what all the valueobject lovers REALLY want anyway
So you're talking overloading objects, rather than extending? Basically, just to create very lightweight value objects? In which case yeah, I'd be happy enough for that. Progress is progress :) Thanks
On the with()
method on the immutable structs, would that always return a new struct? If you're chaining these then you'd be returning a new struct just to throw them away? Would they be built by reference, or would they be new and independent?
Presumably each with() call would return a new struct instance, but with PHP's copy-on-write the memory impact should be minimal. That's how PSR-7 works, and the initial benchmarks said it was cheap enough to do.
And I guess now I see the point of nullables, since without them a struct would only sort of function. Unless we allowed a property to have a default value defined, so even $r = Rectangle{}; would give a valid set of values. Honestly I think I prefer that to nullable, as nulls are nothing but a source of pain and suffering.
That is, you'd have:
struct Rectangle {
int $x = 0;
int $y = 0;
float $width = 0;
float $height = 0;
}
$r = Rectangle{};
print $r->x; // prints 0.
That way there's still never a null.
👍 I would like to see in addition:
and