現在の言語: 日本語 |
PHPの可変長引数 |
引数 |
class test1
{
function test1(...$data):int
{
$total = 0;
for($i=0; $i < count($data); $i++) $total += $data[$i];
return $total;
}
function test2($str, ...$data):string
{
foreach($data as $tmp) $str.=$tmp;
return $str;
}
function test3(int ...$num):int
{
$total = 0;
foreach($num as $tmp) $total += $tmp;
return $total;
}
function test4(...$num):int
{
$total = 0;
foreach($num as $tmp) $total += $tmp;
return $total;
}
}
echo "<pre>";
$cls1= new test1();
echo $cls1->test1(1,2,3).PHP_EOL;//6
$tmp = "ghijk";
echo $cls1->test2("a","bc", "def", $tmp).PHP_EOL;//abcdefghijk
echo $cls1->test3(1,2,3,4,5,6,7,8,9,10).PHP_EOL;//55
echo $cls1->test3(1,"2",3).PHP_EOL;//6
//echo $cls1->test3(1,"aaa",3).PHP_EOL;//Fatal error: Uncaught TypeError: test1::test4(): Argument #2 must be of type int, string given
$ary=[];
for($i=0; $i < 10; $i++)
{
$ary[] =$i+1;
}
var_dump($ary);
/*
array(10) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
}
*/
echo $cls1->test4(...$ary).PHP_EOL;//55
echo "</pre>";
class test1
{
function test1(...$data):int
{
$total = 0;
for($i=0; $i < count($data); $i++) $total += $data[$i];
return $total;
}
function test2($str, ...$data):string
{
foreach($data as $tmp) $str.=$tmp;
return $str;
}
function test3(int ...$num):int
{
$total = 0;
foreach($num as $tmp) $total += $tmp;
return $total;
}
function test4(...$num):int
{
$total = 0;
foreach($num as $tmp) $total += $tmp;
return $total;
}
}
echo "<pre>";
$cls1= new test1();
echo $cls1->test1(1,2,3).PHP_EOL;//6
$tmp = "ghijk";
echo $cls1->test2("a","bc", "def", $tmp).PHP_EOL;//abcdefghijk
echo $cls1->test3(1,2,3,4,5,6,7,8,9,10).PHP_EOL;//55
echo $cls1->test3(1,"2",3).PHP_EOL;//6
//echo $cls1->test3(1,"aaa",3).PHP_EOL;//Fatal error: Uncaught TypeError: test1::test4(): Argument #2 must be of type int, string given
$ary=[];
for($i=0; $i < 10; $i++)
{
$ary[] =$i+1; }
var_dump($ary);
/*
array(10) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
}
*/
echo $cls1->test4(...$ary).PHP_EOL;//55
echo "</pre>";
| 著作権情報 |
| ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。 ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、 または公開したりすることはできません。 当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、 その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について 一切の責任を負わないものとします。 |