PHP method that returns interface instance into array
P粉488464731
P粉488464731 2023-09-01 13:40:43
0
1
495
<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>
P粉488464731
P粉488464731

reply all(1)
P粉447495069

You need to create an extra class called Site and return an array of objects.

class Site
{
    private int $siteId;
    private string $name;
    private string $bone;

    /**
     * @param int    $siteId
     * @param string $name
     * @param string $bone
     */
    public function __construct(int $siteId, string $name, string $bone)
    {
        $this->siteId = $siteId;
        $this->name = $name;
        $this->bone = $bone;
    }

    /**
     * @return int
     */
    public function getSiteId(): int
    {
        return $this->siteId;
    }

    /**
     * @param int $siteId
     */
    public function setSiteId(int $siteId): void
    {
        $this->siteId = $siteId;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName(string $name): void
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getBone(): string
    {
        return $this->bone;
    }

    /**
     * @param string $bone
     */
    public function setBone(string $bone): void
    {
        $this->bone = $bone;
    }

}

Then return the site array:

        return
            [
                (new Site(1, '开罗', 'T-Rex骨骼')),
                (new Site(2, '吉萨', '迅猛龙骨骼')),
                (new Site(3, '亚历山大', '腕龙骨骼'))
            ];
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!