PHP method that returns interface instance into array
P粉488464731
2023-09-01 13:40:43
<p>I have a small question that I can't find the answer to on the internet and I'm not really sure how php and the interface work. </p>
<p>So the problem is I have an if(!variable instanceof class). But here, the class being checked is an interface and should be in an array, you can see in the following code </p>
<pre class="brush:php;toolbar:false;">abstract class Action
{
final public function call(Bone $bone)
{
$sites = $this->getSites($bone);
foreach ($sites as $site) {
if (!$site instanceof Site) {
throw new \Exception("Invalid entry");
}
}
}
}
class BonesSites
{
public function getSites(string $site): array
{
if ($site === 'Egypt') {
return [
[
'siteId' => 1,
'name' => 'Cairo',
'bone' => 'T-Rex bones',
],
[
'siteId' => 2,
'name' => 'Giza',
'bone' => 'Raptors bones',
],
[
'siteId' => 3,
'name' => 'Alexandria',
'bone' => 'Bronchiosaurus bones',
],
];
}
return ['error' => 'Site not found!'];
}
}
interfaceBone
{
public function getName(): string;
}
interface site
{
}</pre>
<p>Is there any way to return an interface in an array? </p>
You need to create an extra class called Site and return an array of objects.
Then return the site array: