diff --git a/Generator/PHPFile.php b/Generator/PHPFile.php
index <HASH>..<HASH> 100644
--- a/Generator/PHPFile.php
+++ b/Generator/PHPFile.php
@@ -195,14 +195,14 @@ class PHPFile extends File {
     $imports = [];
 
     if ($imported_classes) {
-      // Sort the imported classes.
-      natcasesort($imported_classes);
-
       foreach ($imported_classes as $fully_qualified_class_name) {
         $fully_qualified_class_name = ltrim($fully_qualified_class_name, '\\');
         $imports[] = "use $fully_qualified_class_name;";
       }
 
+      // Sort the imported classes.
+      natcasesort($imports);
+
       $imports[] = '';
     }
Fixed sorting should happen after trimming.