File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ --TEST--
2+ Serialization works
3+ --FILE--
4+ <?php
5+
6+ data class Point {
7+ public function __construct (public int $ x , public int $ y ) {}
8+ }
9+
10+ $ p = new Point (1 , 2 );
11+ $ s = serialize ($ p );
12+ var_dump ($ s );
13+ $ p2 = unserialize ($ s );
14+ var_dump ($ p2 === $ p );
15+ ?>
16+ --EXPECT--
17+ string(40) "O:5:"Point":2:{s:1:"x";i:1;s:1:"y";i:2;}"
18+ bool(true)
Original file line number Diff line number Diff line change 1+ --TEST--
2+ Other features work with data classes
3+ --FILE--
4+ <?php
5+
6+ interface Point {
7+ public function add (Point $ point ): Point ;
8+ public float $ length { get; }
9+ }
10+
11+ trait PythagoreanTheorem {
12+ public readonly float $ length ;
13+
14+ public function memoizeLength (): void {
15+ $ this ->length = sqrt ($ this ->x ** 2 + $ this ->y ** 2 );
16+ }
17+ }
18+
19+ final readonly data class Point2D implements Point {
20+ use PythagoreanTheorem; // contains implementation of $length
21+
22+ public function __construct (public int $ x , public int $ y ) {
23+ $ this ->memoizeLength (); // from the trait
24+ }
25+
26+ public function add (Point $ point ): Point {
27+ return new static ($ this ->x + $ point ->x , $ this ->y + $ point ->y );
28+ }
29+ }
30+
31+ $ p1 = new Point2D (1 , 1 );
32+ $ p2 = new Point2D (2 , 2 );
33+ $ p3 = $ p1 ->add ($ p2 );
34+ echo $ p3 ->length , "\n" ;
35+ ?>
36+ --EXPECT--
37+ 6
You can’t perform that action at this time.
0 commit comments