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
class
<?php
class int
{
protected $value;
public function __construct($value)
{
if (!preg_match("/^(0|[-]?[1-9][0-9])*$/", "$value"))
{
throw new \Exception("{$value} is not a valid integer.");
}
$this->value = $value;
}
public function __toString()
{
return '' . $this->value;
}
}
Demo
$test = new int(42);
myFunc($test);
function myFunc(int $a) {
echo "The number is: $a\n";
}
Result
KolyMac:test ninsuo$ php types.php
The number is: 42
KolyMac:test ninsuo$
But you should be careful about side effects.
Your int
instance will evaluate to true
if you're using it inside an expression (such as, $test + 1
), instead of 42
in our case. You should use the "$test" + 1
expression to get 43
, 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
class
<?php
class float
{
protected $value;
public function __construct($value)
{
if (!preg_match("/^(0|[-]?[1-9][0-9]*[\.]?[0-9]*)$/", "$value"))
{
throw new \Exception("{$value} is not a valid floating number.");
}
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
}
The string
class
<?php
class string
{
protected $value;
public function __construct($value)
{
if (is_array($value) || is_resource($value) || (is_object($value) && (!method_exists($value, '__toString'))))
{
throw new \Exception("{$value} is not a valid string or can't be converted to string.");
}
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
}
The bool
class
class bool
{
protected $value;
public function __construct($value)
{
if (!strcasecmp('true', $value) && !strcasecmp('false', $value)
&& !in_array($value, array(0, 1, false, true)))
{
throw new \Exception("{$value} is not a valid boolean.");
}
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
}
The object
class
class object
{
protected $value;
public function __construct($value)
{
if (!is_object($value))
{
throw new \Exception("{$value} is not a valid object.");
}
$this->value = $value;
}
public function __toString()
{
return $this->value; // your object itself should implement __tostring`
}
}