PHP: データ型

PHP: データ型

August 24, 2020
PHP
PHP

データの型について。PHP におけるプリミティブなデータ型は10種類ある。

スカラー型 #

boolean integer float string

複合型 #

array object callable iterable

特別な型 #

resource NULL

型情報を取得する - gettype() #

return values of gettype():
       TRUE is <?php echo gettype(TRUE); ?> 
          1 is <?php echo gettype(1); ?> 
        1.0 is <?php echo gettype(1.0); ?> 
      "str" is <?php echo gettype("str"); ?> 
    array() is <?php echo gettype(array()); ?> 
new class{} is <?php echo gettype(new class{}); ?> 
    fopen() is <?php echo gettype(fopen(__FILE__, "r")); ?> 
       NULL is <?php echo gettype(NULL); ?> 

出力結果。

return values of gettype():
       TRUE is boolean 
          1 is integer 
        1.0 is double 
      "str" is string 
    array() is array 
new class{} is object 
    fopen() is resource 
       NULL is NULL 

gettype()callableiterable は返さない(それらは object

型を判別する - is_*() #

is_book() is_int() is_float() is_string() is_array() is_object() is_callable() is_iterable() is_resource() is_null()

無名関数は is_object()is_callable() で TRUE になるのかな?試してみた。

<?php
$fn = function() {};
$it = array();
?>
  is_object($fn) is <?php echo is_object($fn) ?> 
is_callable($fn) is <?php echo is_callable($fn) ?> 
   is_array($it) is <?php echo is_array($it) ?> 
is_iterable($it) is <?php echo is_iterable($it) ?> 

出力結果。

  is_object($fn) is 1 
is_callable($fn) is 1 
   is_array($it) is 1 
is_iterable($it) is 1 

var_dump() で出力してみる #

var_dump() で型と値をまとめて確認できる。

<?php
var_dump(
  TRUE,
  1,
  1.0,
  "str",
  array(),
  new class() {},
  fopen(__FILE__, "r"),
  NULL,
);
bool(true)
int(1)
float(1)
string(3) "str"
array(0) {
}
object(class@anonymous)#1 (0) {
}
resource(5) of type (stream)
NULL

型キャスト #

PHP ではコンテキストによって暗黙的に型変換が行われる。明示的に型変換をする場合は (type) $val という記述で型キャストが行える。

<?php
var_dump(
  (bool) 1,
  (float) 1,
  (double) 1,
  (string) 1,
);
bool(true)
float(1)
float(1)
string(1) "1"

bool キャスト で false になる値 #

  • 0 , 0.0
  • "" (空文字列)
  • "0"
  • array() (空配列)
  • NULL

文字列の "0"false になって、文字列の "false"true になるのは罠っぽい。

<?php
var_dump(array(
  "(bool) 0"   => (bool) 0,
  "(bool) 1"   => (bool) 1,
  "(bool) 0.0"  => (bool) 0.0,
  "(bool) 1.0"  => (bool) 1.0,
  "(bool) \"\""  => (bool) "",
  "(bool) \"str\""  => (bool) "str",
  "(bool) \"0\""  => (bool) "0",
  "(bool) \"false\""  => (bool) "false",
  "(bool) array()"  => (bool) array(),
  "(bool) array(1,2,3)"  => (bool) array(1,2,3),
  "(bool) NULL"  => (bool) NULL,
));
array(11) {
  ["(bool) 0"]=>
  bool(false)
  ["(bool) 1"]=>
  bool(true)
  ["(bool) 0.0"]=>
  bool(false)
  ["(bool) 1.0"]=>
  bool(true)
  ["(bool) """]=>
  bool(false)
  ["(bool) "str""]=>
  bool(true)
  ["(bool) "0""]=>
  bool(false)
  ["(bool) "false""]=>
  bool(true)
  ["(bool) array()"]=>
  bool(false)
  ["(bool) array(1,2,3)"]=>
  bool(true)
  ["(bool) NULL"]=>
  bool(false)
}