Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dev19's avatar
Level 1

how to instantiate an interface with a class in PHP?

<?php
interface ParentInterface {
    public function sayHi() : string;
}
class A implements ParentInterface {
    private function foo(){
        return 'foo';
    }
    
     public function sayHi() : string {
         echo 'hi!' . $this->foo();
     }
}

class B implements ParentInterface {
    private function bar(){
        return 'bar';
    }
    
    public function sayHi() : string {
         echo 'hi!' . $this->bar();
     }
}
$binded = new ParentInterface;
//how I will tell the interface to instantiate that class I want on the base of some condition.
var_dump($binded->sayHi());
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You cannot. You can never new an interface

You use a service container to return the correct one. In Laravel that might look like this (it requires that you bind it first)

$a = app(ParentInterface::class);

Or you can set the interface as a parameter in a method, and then pass the actual class manually

Example

class FooBar
{

public function foo(ParentInterface $parent) 
{

}
}

and the you can pass in the class

$foobar = new FooBar;
$foobar->foo(new A);
1 like
dev19's avatar
Level 1
<?php

interface TranslationServiceInterface {
    public function sayHi() : string;
}

class ServiceA implements TranslationServiceInterface {
    private function foo(){
        return ' from ServiceA';
    }
    
     public function sayHi() : string {
         return 'hi!' . $this->foo();
     }
}

class ServiceB implements TranslationServiceInterface {
    private function bar(){
        return ' from ServiceB';
    }
    
    public function sayHi() : string {
         return 'hi!' . $this->bar();
     }
}


class ControllerClass {
    private TranslationServiceInterface $repository;
    public function __construct(TranslationServiceInterface $repoistory){
        $this->repository = $repoistory;
    }
    
    public function doSomthingOnBaseOfInterface(){
        return $this->repository->sayHi();
    }
}

$service = 'A';
$calling = match($service){
    'A' => new ControllerClass(new ServiceA),
    'B' => new ControllerClass(new ServiceB),
    default => new ControllerClass(new ServiceA)
};


var_dump($calling->doSomthingOnBaseOfInterface());

Please or to participate in this conversation.