2

I have a type hint in the constructor but for some reason I get

Catchable fatal error: Argument 1 passed to Log::__construct() must be an instance of TestInterface, instance of Log\Handler given, called in 

TestInterface.php

namespace Log;  
    interface TestInterface
    {
      public function log();
    }

Handler.php

namespace Log;

require_once 'TestInterface.php';

use Log\TestInterface;

    class Handler implements TestInterface 
    {
      public function log() 
      {
        //some logic goes here 
      }
    }

Log.php

require_once 'Handler.php';

use Log\Handler;
class Log 
{
  public function __construct(TestInterface $handler)
  {
    $handler->log('test');
  }
}

$obj = new Log(new Handler());

So why do I get this error? I thought that when I implement the TestInterface the instance of Handler class will be passed through the Log constructor.

1 Answer 1

2

You have to add use Log\TestInterface; to the top of Log.php, because TestInterface is undefined in the global namespace. What you got back was not a helpful error message at all, but this should do it:

require_once 'Handler.php';

use Log\Handler;
use Log\TestInterface;

class Log 
{
  public function __construct(TestInterface $handler)
  {
    $handler->log('test');
  }
}

$obj = new Log(new Handler());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This did the job. Is there an another solution of the problem?
@MZON I truly don't think so, but I'm here to learn as well and am open to ideas :). The problem would've been clearer if it said 'TestInterface is not defined' instead of how it's currently described as 'Argument 1 must be an instance of a class/interface that doesn't exist'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.