• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Method __toString is not implemented

LPH

Well-known member
#1
Type hinting was added to a foreach loop and immediately a message popped up that the method __toString is not implemented for $online['username']. It isn't and I'm only learning about magic methods.

Is there a good tutorial on how to properly implement the __toString method?

According to the PHP Manual:
The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.
Maybe there is a better way to implement this loop to pull the $online['username']. After all, this is modified from XenForo 1.

PHP:
/** @var XenWord_Online_Users[] $online */
foreach ( $onlineUserList AS $online ) {
   $user_id = $online['user_id'];
   $url = \XF::app()->router()->buildLink( 'canonical:members', $online );

   echo '<div class="onlineUsers_avatar"><a href="'
        . $url
        . '" title="' . $online['username']
        . '">'
        . get_avatar( $user_id, 32 )
        . '</a></div>';
}
 

LPH

Well-known member
#2
Changed $online['username'] to $online->username and included typehinting. It turns out the typehinting was the key and didn't really need to change to the ->.


PHP:
/** @var XenWord_Online_Users[] $online */
foreach ( $onlineUserList AS $key =>$online ) {
   $user_id = $online['user_id'];
   $url = \XF::app()->router()->buildLink( 'canonical:members', $online );

   /** @var $online */
   echo '<div class="onlineUsers_avatar"><a href="'
        . $url
        . '" title="' . $online->username
        . '">'
        . get_avatar( $user_id, 32 )
        . '</a></div>';
}