Can’t Write Custom Widget Code In One ECHO

Technically your first example is also incorrect, but the problem is not apparent. You’re using template tags that themselves echo their content. For example, you can write simply:

the_permalink();

without echo, and the permalink will be output. This is because that function echoes its value. To output the permalink within an echo or variable assignment you need to use get_permalink:

echo get_permalink()

Just about all WordPress template tags have equivalent get_ versions, or an argument that toggles echo and return, like the_title:

the_title( '', '', false );

Here the 3rd parameter toggles echo (true) or return (false).

error code: 523