現在の言語: 日本語

戻る

配列形式としてコールバック関数
コールバック関数

[コールバック関数について]
PHPのcallableとは、「関数として呼び出すことができるデータ型」を表す型ヒントです。
関数が引数として別の関数を受け取る(高階関数)際などに、
「実行可能なものだけを許可する」ために使用されています。
※PHP 5.4から使用可能
配列形式としてコールバック関数を実行

静的メソッド
(例)
['testClass', 'testMethod']

インスタンスメソッド
(例)
[$cls, 'testMethod']

[サンプル]

copy
class test1
{
	function test1():void
	{
		echo "test1 execute".PHP_EOL;
	}
	function test2(int $num1, int $num2):int
	{
		return $num1 + $num2;
	}
	function test3(int &$result, array $ary):void
	{
		$result = 0;
		for($i=0; $i < count($ary); $i++)
		{
			$result += $ary[$i];
		}
	}
	static function test4()
	{
		echo "test4".PHP_EOL;
	}
}
echo "<pre>";
$cls1= new test1();
//配列形式
//[$インスタンス, 'メソッド名'] という配列
$test1 = [$cls1, 'test1'];
$test2 = [$cls1, 'test2'];
$test3 = [$cls1, 'test3'];
$result = 0;
$test1();
/*
test1 execute
*/
$num1 = 1;
$num2 = 2;
$ary = [];
for($i=0; $i<3; $i++)$ary[] = $i +1;
echo $test2($num1, $num2) . PHP_EOL;//3
// 参照渡しも維持されます
$test3($result, $ary); 
echo "result:$result".PHP_EOL;//result:6
//静的メソッド
$static = ["test1", "test4"];
$static().PHP_EOL;//test4
echo "</pre>";
copy
class test1
{
	function test1():void
	{
		echo "test1 execute".PHP_EOL;
	}
	function test2(int $num1, int $num2):int
	{
		return $num1 + $num2;
	}
	function test3(int &$result, array $ary):void
	{
		$result = 0;
		for($i=0; $i < count($ary); $i++)
		{
			$result += $ary[$i];
		}
	}
	static function test4()
	{
		echo "test4".PHP_EOL;
	}
}
echo "<pre>";
$cls1 = new test1();
//Array format
//Array of [$instance, 'method name']
$test1 = [$cls1, 'test1'];
$test2 = [$cls1, 'test2'];
$test3 = [$cls1, 'test3'];
$result = 0;
$test1();
/*
test1 execute
*/
$num1 = 1;
$num2 = 2;
$ary = [];
for($i=0; $i<3; $i++)$ary[] = $i +1;
echo $test2($num1, $num2) . PHP_EOL;//3
// Passing by reference is also maintained
$test3($result, $ary);
echo "result:$result".PHP_EOL;//result:6
//Static method
$static = ["test1", "test4"];
$static().PHP_EOL;//test4
echo "
";

種類従来の配列形式 (PHP 5.4+)モダンな書き方 (PHP 8.1+)
静的["testClass", "test1"]testClass::test1(...)
インスタンス[$cls, 'test1']$cls->test1(...)


戻る

著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。