In new PHP i can type. Whats better to type?
Use class:
<?php
class Animal {
protected string $name;
}
class Cat extends Animal {
}
class Dog extends Animal {
}
function doSth(Animal $animal): Animal {
return $animal;
}
$cat = new Cat();
doSth($cat);
or use interfaces?
<?php
interface Animal {
public function doSth(): string;
}
class Cat implements Animal {
public function doSth(): string {
return "purr";
}
}
function doSth(Animal $animal): string {
return $animal->doSth();
}
$cat = new Cat();
doSth($cat);
And how it works it’s fine if iI call to base/parent class in typing or better solution is to use:
function doSth(Cat|Dog $animal): Cat|Dog
I expect to get knowledge what’s better practise
New contributor
w5s is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.