interface ExtractorInterface
{
/**
* @param object $object
* @return array
*/
public function extract(object $object);
}
class MyObjectExtractor implements ExtractorInterface
{
/**
* @param MyObject $object
* @return array
*/
public function extract(MyObject $object)
{
return [
'a' => $object->a,
];
}
}
class MyObject
{
public $a;
}
<?php
class ArrayClass {
public function foo(array $foo) { /* ... */ }
}
// This RFC proposes allowing the type to be widened to be untyped aka any
// type can be passed as the parameter.
// Any type restrictions can be done via user code in the method body.
class EverythingClass extends ArrayClass {
public function foo($foo) { /* ... */ }
}
Задался вопросом почему объект класса не совместим с типом object.Наоборот - это object несовместим с MyObject.
interface Extractable
{
public function extract(): array;
}
class MyObject implements Extractable
{
public $a;
public function extract(): array
{
return [
'a' => $this->a,
];
}
}
class MyOtherObject implements Extractable
{
public $a, $b, $c;
public function extract(): array
{
return [
'a-b' => $this->a . $this->b,
'c' => $this->c->toArray(),
];
}
}