从 PHP 5 开始,PHP 允许 type hinting 使用类(强制函数/方法的参数成为类的实例)。
因此,您可以创建一个int 类,该类在构造函数中采用 PHP 整数(如果您允许包含整数的字符串,则解析整数,如下例所示),并在函数的参数中期望它。
int 类
<?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;
}
}
演示
$test = new int(42);
myFunc($test);
function myFunc(int $a) {
echo "The number is: $a\n";
}
结果
KolyMac:test ninsuo$ php types.php
The number is: 42
KolyMac:test ninsuo$
但你应该小心副作用。
如果您在表达式中使用int 实例(例如$test + 1),则其计算结果将是true,而不是我们的例子中的42。您应该使用"$test" + 1 表达式来获取43,因为__toString 仅在尝试将您的对象转换为字符串时被调用。
注意:您不需要包装 array 类型,因为您可以在函数/方法的参数上进行原生类型提示。
float 类
<?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;
}
}
string 类
<?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;
}
}
bool 类
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;
}
}
object 类
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`
}
}