LoginSignup
0
0

More than 1 year has passed since last update.

PHP関数の型の指定方法について...

Last updated at Posted at 2021-11-14

PHP型付けについて



引数や返り値に、文字列、整数値しか受け付けないように型を指定していきます!

以下の関数があったとします。

index.php
<?php
function show($name, $score) {
  echo $name . ': ' . $score . PHP_EOL;
}

show('kana', 'kana');



$name と $score の引数の前に型を指定していきます!

string は文字列で、

int は整数値を指定します!

index.php
<?php
function show(string $name, int $score) {
  echo $name . ': ' . $score . PHP_EOL;
}

show('kana', 'kana');



ターミナルで以下を実行すると...

~$ php index.php



show( 'kana', 'kana' ) ; の2番目の引数に文字列が入っているのでエラーになります!

2番目の引数を整数値に変えてみます。

index.php
<?php
function show(string $name, int $score) {
  echo $name . ': ' . $score . PHP_EOL;
}

show('kana', 2);



ターミナルで以下を実行すると...

~$ php index.php



ちゃんと出力されました!

~ $ php index.php
kana: 2
~ $ 



さらに強い型付けを指定するには、

declare ( strict_types = 1 ); を最初につけます。

index.php
<?php

declare(strict_types=1);

function show(string $name, int $score) {
  echo $name . ': ' . $score . PHP_EOL;
}

show('kana', 2);



declare ( strict_types = 1 ); をつける事で厳密に型のチェックができます。

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