Rohit Khatri Rohit Khatri - 16 days ago 5
PHP Question

Allow object as parameter only if extends particular class in php

How can I restrict class

method
to take only
object
of a
class
which extends a particular class?

Code:

Serializer Interface

namespace App\API\Serializers;

use Illuminate\Database\Eloquent\Model;

interface Serializer
{
public function serialize(Model $model);
}


namespace App\API\Serializers;

use App\API\Serializers\Serializer;
use App\Models\Article;

class MilestoneListSerializer implements Serializer
{
public function serialize(Article $article)
{

}
}


I want to pass
Article
as parameter and It's extending
Illuminate\Database\Eloquent\Model
class

Is there any way to do this, please help me.

Any help is appreciated. Thanks.

Answer

You are changing the Serializer interface serialize method signature when you alter the parameter from Model to Article. You should keep the Model, and if the Article extends Model, then you will be able to pass it to the method.

Interface Serializer

namespace App\API\Serializers;

use Illuminate\Database\Eloquent\Model;

interface Serializer
{
    public function serialize(Model $modelOrItsSubTypes);
}

MilestoneListSerializer

namespace App\API\Serializers;

use App\API\Serializers\Serializer;
use App\Models\Article;

class MilestoneListSerializer implements Serializer
{
    public function serialize(Model $modelOrItsSubTypes)
    {
        // ... Use Model methods here
    }
}

Article

namespace App\Somenamespace;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    //.. Overrides here
}
Comments