<?php
interface MyInterface {
public function get(): int;
public function set(int $value);
}
class Factory {
private $instance = null;
public function getInstance(): MyInterface
{
if ($this->instance === null) {
$this->instance = new class() {
private $var;
public function get(): int {
return $this->var;
}
public function set(int $value) {
$this->var = $value;
}
};
}
return $this->instance;
}
}
function display(MyInterface $object)
{
var_dump($object->get());
}
$factory = new Factory();
$o = $factory->getInstance();
$o->set(5);
$o2 = $factory->getInstance();
display($o2);
Fatal error: Uncaught TypeError: Factory::getInstance(): Return value must be of type MyInterface, class@anonymous returned in /in/ogcL0:25
Stack trace:
#0 /in/ogcL0(35): Factory->getInstance()
#1 {main}
thrown in /in/ogcL0 on line 25
Process exited with code 255.
Fatal error: Uncaught TypeError: Return value of Factory::getInstance() must implement interface MyInterface, instance of class@anonymous returned in /in/ogcL0:25
Stack trace:
#0 /in/ogcL0(35): Factory->getInstance()
#1 {main}
thrown in /in/ogcL0 on line 25
Process exited with code 255.