codeigniter4 / CodeIgniter4

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
5.39k stars 1.9k forks source link

Bug: Cannot instantiate interface #6631

Closed Salman98 closed 2 years ago

Salman98 commented 2 years ago

PHP Version

8.1

CodeIgniter4 Version

4.2.6

CodeIgniter4 Installation Method

Manual (zip or tar.gz)

Which operating systems have you tested for this bug?

Linux

Which server did you use?

fpm-fcgi

Database

No response

What happened?

Error : Cannot instantiate interface .

I have following files

HomeController

 class Home extends BaseController
{
    public function __construct() 
    {
        $this->test = new UserInterface();
    }

    public function index ()
    {

        $this->test->login('username', 'password');

    }
}

In Config/AutoLoad.php I added these too

 public $classmap = [
     UserRepository::class => APPPATH . 'Repositories/Users/UserRepository.php',
     UserInterface::class => APPPATH .  'Interfaces/Users/UserInterface.php',
    ];

Steps to Reproduce

I have added code , if you try to follow it you will be able to reproduce it

Expected Output

the interface should work but it's not working

Anything else?

No response

kenjis commented 2 years ago

Sorry, PHP cannot instantiate interface. https://www.php.net/manual/en/language.oop5.interfaces.php

We use GitHub issues to track BUGS and to track approved DEVELOPMENT work packages. We use our forum to provide SUPPORT and to discuss FEATURE REQUESTS.

Salman98 commented 2 years ago

Sorry, PHP cannot instantiate interface. https://www.php.net/manual/en/language.oop5.interfaces.php

We use GitHub issues to track BUGS and to track approved DEVELOPMENT work packages. We use our forum to provide SUPPORT and to discuss FEATURE REQUESTS.

I didn't find answer then I had no choice to post here . If you know already what i am missing then please let me know in future it might be useful for others too . Thanks

kenjis commented 2 years ago

As far as I know, interfaces cannot be instantiated. You must instantiate a concrete class that implements the interface.

paulbalandan commented 2 years ago

I think you mean to instantiate UserRepository, the concrete implementation of UserInterface.

class Home extends BaseController
{
   public function __construct() 
   {
-      $this->test = new UserInterface();
+      $this->test = new UserRepository();
   }

   public function index ()
   {

       $this->test->login('username', 'password');

   }
}