Ite*_*tor 7 php boxing type-conversion type-hinting php-7
在php-s类型提示中,我不能使用标量类型,如整数或字符串.所以这是无效的:
function myFunc(int $num) {
//...
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用包装类,如JAVA?整数,字符串,布尔值等...
我想像这样使用它:
function myFunc(Integer $num) {
//...
}
myFunc(5); // ok
myFunc("foo"); // error
Run Code Online (Sandbox Code Playgroud)
我知道,默认情况下,php中没有包装类.但怎么可能写一个呢?
从PHP 5开始,PHP允许使用类进行类型提示(强制函数/方法的参数成为类的实例).
因此,您可以创建一个int在构造函数中采用PHP整数的类(如果允许包含整数的字符串,则解析整数,例如下面的示例中),并期望它在函数的参数中.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Demo
$test = new int(42);
myFunc($test);
function myFunc(int $a) {
echo "The number is: $a\n";
}
Run Code Online (Sandbox Code Playgroud)
Result
KolyMac:test ninsuo$ php types.php
The number is: 42
KolyMac:test ninsuo$
Run Code Online (Sandbox Code Playgroud)
但是你应该注意副作用.
如果您在表达式(例如,)中使用它,您的int实例将评估,而不是在我们的情况下.您应该使用表达式来获取,因为只有在尝试将对象转换为字符串时才会调用它.true$test + 142"$test" + 143__toString
注意:您不需要包装array类型,因为您可以在函数/方法的参数上本地键入提示.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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`
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
526 次 |
| 最近记录: |