use keyword

What is the use Keyword in PHP?

  • Profile picture of Mcs
  • by Mcs July 1, 2025

In Drupal, the use keyword in PHP is used primarily for importing classes, traits, interfaces, or namespaces into the current file or scope, so that you can reference them without writing the full namespace path every time.

Why use is important in Drupal

Drupal 8 and later versions are built on modern PHP practices, including object-oriented programming (OOP) and namespaces. As such, the use keyword is used frequently throughout Drupal code to make class references cleaner and more readable.

Syntax:

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

Example:

<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyForm extends FormBase {

 public function getFormId() {
   return 'my_form';
 }

 public function buildForm(array $form, FormStateInterface $form_state) {
   $form['name'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Name'),
   ];
   return $form;
 }

 public function submitForm(array &$form, FormStateInterface $form_state) {
   \Drupal::messenger()->addMessage($this->t('Form submitted!'));
 }
}

Without the use statements, you would have to reference full paths like:

$form_state instanceof \Drupal\Core\Form\FormStateInterface

Key Points:

  • Helps avoid long, fully qualified class names.
  • Required when using classes or interfaces from other namespaces.
  • Makes code cleaner, easier to read, and maintain.

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.