Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Checking my code with DrupalPractice standard I found code sniffer warns for every line contains $this or any other properties defined by the same trait.
Here my example trait:
/**
* @file
* Contains \Drupal\MY_MODULE\LangcodeTrait.
*/
namespace Drupal\MY_MODULE;
/**
* A trait containing helper methods for language handling.
*/
trait LangcodeTrait {
/**
* Name of language.
*
* @var string
*/
protected $langcode;
/**
* A fully-populated language object.
*
* @var \Drupal\core\Language\LanguageInterface|null
*/
protected $lang;
/**
* Select language.
*
* @param string $langcode
* Language code.
*
* @return $this
* Current instance.
*/
public function setLangcode($langcode) {
$this->langcode = $langcode;
$this->lang = \Drupal::languageManager()->getLanguage($this->langcode);
return $this;
}
/**
* Get code of currently active language.
*
* @return string
* Language code.
*/
public function getLangcode() {
if (!isset($this->langcode)) {
$lang = \Drupal::languageManager()->getCurrentLanguage();
$this->setLangcode($lang->getId());
}
return $this->langcode;
}
}
Result:
FILE: [...]/src/LangcodeTrait.php
----------------------------------------------------------------------
FOUND 0 ERRORS AND 9 WARNINGS AFFECTING 8 LINES
----------------------------------------------------------------------
19 | WARNING | Variable $langcode is undefined.
26 | WARNING | Variable $lang is undefined.
38 | WARNING | Variable $this is undefined.
39 | WARNING | Variable $this is undefined.
39 | WARNING | Variable $this is undefined.
40 | WARNING | Variable $this is undefined.
50 | WARNING | Variable $this is undefined.
52 | WARNING | Variable $this is undefined.
55 | WARNING | Variable $this is undefined.
Comments
Comment #3
klausiCommitted a fix, thanks for reporting!