rink.attendant.6 rink.attendant.6 - 1 year ago 106
PHP Question

PHP sprintf %d behaviour

Is it safe to assume that

will always try to cast the parameter to an integer when using
in PHP?

For example:


echo sprintf('Hello %d', 'foo');
echo sprintf('Hello %d', -1);
echo sprintf('Hello %d', 1);
echo sprintf('Hello %d', 0.1);
echo sprintf('Hello %d', true);
echo sprintf('Hello %d', false);
echo sprintf('Hello %d', null);
echo sprintf('Hello %d', array('foo'));
echo @sprintf('Hello %d', new stdClass());

I am not using this to prevent SQL injections (already have parameterized queries in my application) but rather to construct query parameters in a URL.

Answer Source

It's clearly documented: Variables will be co-erced to a suitable type for the specifier.

Passing an object to something that expects a string(say) will require the object to implement the magic __toString() method, however. PHP will not be able to convert ALL types, just ones it knows how to do so.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download