7

php-s の型ヒントでは、整数や文字列などのスカラー型を使用できません。したがって、これは無効です。

function myFunc(int $num) {
    //...
}

JAVA のようにラッパー クラスを使用することはできますか? 整数、文字列、ブール値など...

次のように使用したいと思います。

function myFunc(Integer $num) {
    //...
}

myFunc(5);     // ok
myFunc("foo"); // error

デフォルトでは、phpにはラッパークラスがありません。しかし、どうやってそれを書くことができるのでしょうか?

4

2 に答える 2

5

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 + 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;
   }

}

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`
   }

}
于 2014-11-19T13:51:54.957 に答える