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, the error will be slightly different. For example, the name of the function and the class will both be different. A different data type may also be mentioned at the end of the error message.

Type hints.

Take a look at the following function, which is using a type hint.

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

In this case, the function takes in one parameter.

For this parameter, we are using the type hint Example.

This tells PHP that the parameter $obj must be an Example object. In other words, the variable must have been instantiated from a class called Example.

If we attempt to pass in an integer, a string or an array, the code will throw a fatal error.

Take a look at the following snippet.

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

The code above will throw an error. This is because we are attempting to pass a string into our function instead of an Example object.

To fix the “must be an instance” error, you will need to pass in the correct variable.

The fix in this case might look something like this.

$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 nasty bugs and mistakes, so be extremely careful about taking the lazy route and removing it.