Fix: Argument passed to function() must be an instance of ClassName.

This is a short guide on how to fix the following PHP error:

Catchable fatal error: Argument 1 passed to test() must be an instance of Example, string given.

In your case, this error will be slightly different, depending on the name of the function that you’re calling and the name of the class that is involved.

Type hints.

Let’s take a look at the test function:

function test(Example $obj){
    //Do something
}

In this case, the function takes in one parameter. For this parameter, a type hint has been used. This particular type hint (or type declaration) tells PHP that the function parameter must be an Example object. i.e. The variable must have been instantiated from a class called Example.

Take a look at the following snippet:

//This will cause an error.
test('Hello');

The code above will throw the error that you saw being quoted at the beginning of this post. This error is thrown because we are attempting to pass in a string instead of an Example object.

The fix in this case could look like:

$exampleObj = new Example();
test($exampleObj);

As you can see, we instantiated the Example class and passed our object into the test function.

Type hints like these exist to prevent developers from misusing functions. They help to prevent bugs, so be careful about taking the lazy route and removing it.