2

I have written a custom class contructor (classname UserHandler) where I want to have a parameter which can be an instance of Drupal\user\Entity\User, an integer or FALSE:

  public function __construct($user = FALSE) {
    if ($user && $user instanceof User ) {
      $this->account = $user;
    }

    if ($user && is_int($user)) {
      $this->account = User::load($user);
    }


    if (!$user) {
      $this->account = User::load(Drupal::currentUser()->id());
    }

    $this->setProfileId();
  }

When I instantiate this class by calling UserHandler() or UserHandler($someUserClassInstance) everything works fine. When I want to instantiate this class by using a user id to load the user object in the constructor it works just fine as well: UserHandler(65).

But the problem appears when I want to use the id from any kind of entity or accountproxy class. Example in a hook_node_access:

function custom_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $profile = new IgbUser($account->id());
}

$account is a class instance of Drupal\Core\Session\AccountInterface. When I call $account->id() the value returned is a string not an integer. This leads to the problem that a check like is_int($account->id()) becomes false. This appears with $node->id() as well for example.

Maybe I did not get some basics in PHP classes but all the comments above the id() methods in all the classes state that they would return an integer?!

Best, Tobias

4

The value is in integer (for most content entity types, that is). The variable type however is a string.

That has a simple technical reason, values loaded from the database are always strings, those put into the node object and never explicitly cast to something else. Doing so would be too expensive for what it brings.

3

As @4k4 mentioned, it can be int or string. If the value type does matter to your code. Just force convert it to integer.

(int) $account->id()
1

For User and Node this is defined in the class Drupal\Core\Entity\EntityInterface:

  /**
   * Gets the identifier.
   *
   * @return string|int|null
   *   The entity identifier, or NULL if the object does not yet have an
   *   identifier.
   */
  public function id();

And as far as I checked, all subclasses inherit this doc.

The methods to retrieve the id are defined later in the subclasses, so you have to consider both possibilities string and int in your code, which should be no problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.