1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP 型演算子 instanceofを使って変数を評価する

Posted at

目的

  • PHPの方演算子であるinstanceofを使って評価対象の変数が指定のクラスのオブジェクト変数かどうかをチェックする。

方法

  • 下記のように記載することで指定クラスのオブジェクト変数かどうかをチェックする。

    評価対象の変数 instanceof クラス名
    
  • 評価の結果は真偽値(bool)で返ってくる。(評価対象の変数が指定したクラスのオブジェクト変数だった場合trueが返される。)

  • 参考文献先に下記のようなソースが記載されていた。

    <?php
    class MyClass
    {
    }
    
    class NotMyClass
    {
    }
    
    $a = new MyClass;
    
    var_dump($a instanceof MyClass); //trueを返す
    var_dump($a instanceof NotMyClass); //falseを返す
    
  • $aはMyClassクラスのがインスタンス化されたオブジェクト変数であり、無関係なNotMyClassクラスのオブジェクト変数ではない。

  • よって$a instanceof MyClassはtrueとなる。

参考文献

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?