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;
}
}
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$
しかし、副作用には注意が必要です。
この例ではなく、式 (, など) 内で使用している場合、インスタンスint
は に評価されます。はオブジェクトを文字列にキャストしようとしたときにのみ呼び出されるため、式を使用して get を取得する必要があります。true
$test + 1
42
"$test" + 1
43
__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;
}
}
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`
}
}