User Contributed Notes 2 notes

For backwards compatibility issues:
We do know that auto-unboxing works for strings, thanks to the __toString() magic function. Auto-unboxing for other scalar types may be tricky but possible, by using the same function with another return type (which of cause has some limitations).

However auto-boxing is a real challenge.
If you can provide any details, I would appreciate that.

For other scalar types, all that changes is the constructor function. Anything else remains unchanged. (While you are at it, you may want to add some type conversion functions for your personal convenience.)

This single-line of code should fix it for most people. It will throw an error whenever the expression evaluates to false (if $foo is not a string).

Most errors concerning scalar types are found during development or unit-testing. PHPUnit is fine with these and reports failed assertions as failed tests, also presenting the included message.
Note that assertions need to be turned on for this to work. See the manual page on assertions for more details.
Note that you may deactivate the checks on the target machine, so this comes without any performance penalty. So don't hesitate to make extensive use of this PHP-feature.

Note though: DON'T RELY ON ASSERTIONS FOR CHECKING USER INPUT!

In that case you may want to try this code:
is_string($foo) || trigger_error('String expected', E_USER_ERROR);