In php-s type hinting, I cannot use scalar types, like integer, or string. So this is invalid:
function myFunc(int $num) {
//...
}
Is it possible to use wrapper classes, like in JAVA? Integer, String, Boolean, etc...
I would like to use it like this:
function myFunc(Integer $num) {
//...
}
myFunc(5); // ok
myFunc("foo"); // error
I know, there are no wrapper classes in php by default. But how is it possible, to write one?
Since PHP 5, PHP allows type hinting using classes (forcing a function/method's parameter to be an instance of a classs).
So you can create an
int
class that takes a PHP integer in constructor (or parsing an integer if you allow a string containing an integer, such as in the example below), and expect it in a function's parameter.The
int
classDemo
Result
But you should be careful about side effects.
Your
int
instance will evaluate totrue
if you're using it inside an expression (such as,$test + 1
), instead of42
in our case. You should use the"$test" + 1
expression to get43
, as the__toString
is only called when trying to cast your object to a string.Note: you don't need to wrap the
array
type, as you can natively type-hint it on function/method's parameters.The
float
classThe
string
classThe
bool
classThe
object
class