Your function does indeed do the job, although you could make it simpler by skipping the temporary variable $out and just echo the return value of htmlspecialchars directly.
Personally, I’d prefer the function from the book that returns its output, as it’s more flexible/reusable. With functions that return their output, you have the option to do further processing. With your function, you are forced to echo the output.