Solving Error: Cannot use * as String because 'String' is a special class name

If you've ever seen an error message in your PHP 7 website about 'String' being a special class name, e.g. Error: Cannot use Drupal\Component\Utility\String as String because 'String' is a special class name in /Users/jesus/drush/commands/core/, line 4, the reason is that String is now a reserved class name as of PHP 7. So your code that worked fine on PHP 5.7 and earlier will now be broken. This affects Drupal but could affect any old PHP site with a class called String.

This is a problem with Drupal 8 which moved to an OOP-everywhere approach, so things must now be objects like Drupal\Component\Utility\String except not String. This bug can be seen when using Drush and Views in core and a number of other places. Generally speaking, Drupal 8 is currently broken on PHP 7.

You can patch this yourself just by changing some lines of code and those error messages tell you exactly which file and which line to fix. Or you can find them by running this in your site's root directory (or the location where drush is installed):

grep -r 'use Drupal[\]Component[\]Utility[\]String;' *

You can also fix each file from the command line using sed like so, given a filename:

sed -i -e 's/use Drupal[\]Component[\]Utility[\]String;/use Drupal\\Component\\Utility\\SafeMarkup;/' $filename

You can see that the fix is to replace String with SafeMarkup which works for Drupal. At some point, all of these should be fixed in Drupal. See the Issue: Split Utility\String class to support PHP 7 (String is a reserved word)

Add new comment