What is the output of this PHP code using intersection types?
<?php interface A { public function foo(): string; } interface B { public function bar(): string; } class C implements A, B { public function foo(): string { return 'foo'; } public function bar(): string { return 'bar'; } } function test( A&B $obj ): string { return $obj->foo() . '-' . $obj->bar(); } $c = new C(); echo test($c); ?>
Remember that the function requires an object implementing both interfaces A and B.
The function test accepts an object that implements both interfaces A and B. The class C implements both, so calling test($c) returns foo-bar.
What will this PHP code output?
<?php interface X { public function x(): string; } interface Y { public function y(): string; } class Z implements X, Y { public function x(): string { return 'X'; } public function y(): string { return 'Y'; } } function create(): X&Y { return new Z(); } $obj = create(); echo $obj->x() . $obj->y(); ?>
The function returns an object implementing both interfaces X and Y.
The function create returns an instance of Z which implements both X and Y. So calling $obj->x() and $obj->y() outputs XY.
What error will this PHP code produce?
<?php interface M { public function m(): string; } interface N { public function n(): string; } class P implements M { public function m(): string { return 'm'; } } function callMN(M&N $obj): string { return $obj->m() . $obj->n(); } $p = new P(); echo callMN($p); ?>
Check if the object passed implements both interfaces M and N.
The function callMN requires an object implementing both M and N. The class P only implements M. Passing $p causes a TypeError because P does not implement N.
Which option shows the correct syntax to declare a function parameter with intersection types in PHP?
Intersection types use a single ampersand without spaces.
The correct syntax for intersection types in PHP is A&B without spaces. Option C is correct. Option C has spaces which cause syntax error. Option C uses double ampersand which is invalid. Option C uses pipe which is union type, not intersection.
Given the code below, what will be the output?
<?php interface I1 { public function get(): string; } interface I2 { public function get(): string; } trait T1 { public function get(): string { return 'Trait'; } } class MyClass implements I1, I2 { use T1; } function show(I1&I2 $obj): string { return $obj->get(); } $instance = new MyClass(); echo show($instance); ?>
Traits can provide method implementations for interfaces.
The class MyClass implements both interfaces I1 and I2 and uses trait T1 which provides the get() method. So calling show($instance) outputs Trait.