LoginSignup
12
12

More than 5 years have passed since last update.

PHPでスカラー型の強い型付け

Posted at
<?php
    $object = new stdClass();
    $object = '1' + 1;

    $boolean = ( '1' == 1 );

$objectはint型の2、$booleanはtrueになり、Java出身者が憤死します。
PHPの型の挙動には色々と論がある人も多いですが、PHPの特徴だと思って諦めましょう。
まあ私はこういうの嫌いではないですが、推移律が成り立たないのはさすがにどうかと思う。

しかし時には、どうしても厳密に型を適用したいんだよ、という場合があるかもしれません。
そんなときのためにSplTypeです。

今のところデフォルトでは入ってないのでPECLから持ってきましょう。
Windows版のDLLも存在します。

<?php
    $int = new SplInt(1);

    $int = 2; // 2
    $int++; // 3

    $int = 1.0; // Fatal error: Uncaught exception 'UnexpectedValueException'
    $int = 'a'; // Fatal error: Uncaught exception 'UnexpectedValueException'

    $a = $int + 10; // 13
    for($i=1; $i<$int; $i++){} // 問題なく動作

PHPがあたかもRubyのような強い型付けに!

$intは、intもしくはSplInt以外を代入しようとするとUnexpectedValueExceptionを発生します。
これで$intの型一意性が保証されることになりました。
逆に$intを演算に使う場合は、ただの整数と同じように扱えます。

型付けの対象としては、int以外にfloat、boolean、stringの各スカラー型、そしてEnum型が用意されています。
http://www.php.net/manual/ja/book.spl-types.php

ところで、

スカラー型のタイプヒンティングの代替手段として使用できます。

って書いてあるのですが、あくまで代替のようで完全なタイプヒンティングとしては使えませんでした。

<?php
    class HOGE{

        private $int;

        // setSplIntは呼び出し側でキャストしないといけない
        public function setSplInt(SplInt $int){
            $this->int = $int;
        }

        // setIntは概ね想定した動作だがタイプヒンティングではない
        public function setInt($int){
            $this->int = new SplInt($int);
        }
    }

    $hoge = new HOGE();

    $hoge->setSplInt(new SplInt(1));
    $hoge->setSplInt(1); // Argument 1 must be an instance of SplInt, integer given
    $hoge->setInt(2);
    $hoge->setInt(2.0); // Uncaught exception 'UnexpectedValueException'

まあ後者で作っておけば実質的には困らないと思います。

12
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12