Pathinfo() expects parameter 1 to be string, object given

Error: pathinfo() expects parameter 1 to be string, object given

This error indicates that the pathinfo() function in PHP is expecting a string as its first parameter, but it received an object instead. The pathinfo() function is used to retrieve information about a file path, such as the directory name, filename, extension, etc.

The function requires a string representing the file path as its first argument. However, if an object is passed instead of a string, the function doesn’t know how to handle it and throws this error.

Example

Let’s consider an example where an object is mistakenly passed to the pathinfo() function:

    // An object representing a file path
    $filePath = new stdClass();
    $filePath->path = "/path/to/file.txt";
    
    // Calling the pathinfo function with an object instead of a string
    $fileInfo = pathinfo($filePath);
    
    // This will throw an error like: pathinfo() expects parameter 1 to be string, object given
  

In the above example, we have mistakenly passed an object ($filePath) to the pathinfo() function instead of a string. As a result, the error is thrown.

To fix the error, we need to ensure that we pass a string representing the file path to the pathinfo() function. In the above example, it can be fixed as follows:

    // A string representing the file path
    $filePath = "/path/to/file.txt";
    
    // Calling the pathinfo function with the correct string parameter
    $fileInfo = pathinfo($filePath);
    
    // Now, $fileInfo will contain the file information without any error
  

In the corrected example, we only pass the string representing the file path to the pathinfo() function, which resolves the error.

Leave a comment