What is the best way to extract the namespace of a class in PHP when only the file path is known?

To extract the namespace of a class in PHP when only the file path is known, you can read the contents of the file and use regular expressions to find the namespace declaration. This can be done by searching for a line that starts with "namespace" followed by the namespace name. Once the namespace is extracted, you can use it as needed in your application.

function getNamespaceFromFile($filePath) {
    $fileContents = file_get_contents($filePath);
    preg_match('/namespace\s+([^\s;]+)/', $fileContents, $matches);
    
    if (isset($matches[1])) {
        return $matches[1];
    }
    
    return null;
}

// Usage example
$filePath = 'path/to/YourClass.php';
$namespace = getNamespaceFromFile($filePath);
echo $namespace;