Cannot retrieve username from user ID

I’m trying to retrieve the username from the user ID

<?php $boubou = $comment->commenterID() ?>
<?= $kirby->user($boubou)->username() ?>

commenterID contains the user ID stored in a .txt file. If I echo $boubou by itself, it displays the commenterID properly, however, when I try to get the username based on the ID, it does not work…

I get “Call to a member function username() on null”

Any idea?


oops forgot to add the error message

I assume this comes from a users field?


if ( $user = $comment->commenterID()->toUser() ) {
  echo $user->username();

The users field stores content in yaml format, like this:


- 010101x

And since we cannot trust that what we stored in the content file is still valid years after, we always check if we still have an instance of the user class… Always. No exceptions. Not only for users. But also for files, and pages …

thank you.

Sorry I don’t really understand?

The commenterID comes from a “comment” subpage.
What happens is that when a user writes a comment and posts it, the comment.txt contains the userID under “commenterID”.

We aren’t storing the username or email address in case the username or email address change.

Then on the front end, we are retrieving the comment, and we want to display the username based on the userID (commenterID) stored in this .txt file.

When I run this

echo $kirby->user($commenterID)

it prints the userID, but when I run this

echo $kirby->user($commenterID)->username()

it returns the error

Call to a member function username() on null

Ok, so no users field but just a common field.

Nevertheless, it doesn’t really matter, you should always check if you have a user object before you call a method like username() or any other, for that matter. And never use the code like in your example.

The code I posted should nevertheless work.

If you want to go the $kirby->user() way, you would have to do it correspondingly:

if ( $user = $kirby->user($commenterID)) {
  echo $user->username();

Oh I see!
I just tried

if ( $user = $kirby->user($commenterID)) {
  echo $user->username();

And yes, it does work.
Now I will know !
Is this mentioned anywhere in the documentation? If not, it might be good to have it explained somewhere as I think it is really useful! Unless it’s obvious for everyone else haha

Thank you so much for your help (again!)


Yes, this is mentioned in each class overview with examples, e.g.

Here is a simple example of a class with a method eat()


class ChocolateBar

  public function eat()
    return 'yummy';

$chocolate = new ChocolateBar(); // get some chocolate before you can eat it
echo $chocolate->eat(); // "yummy"

$chocolate = null; // no chocolate instance
echo $chocolate->eat(); // can't eat it, throws error