PHP 배열에 함수를 저장할 수 있습니까?
예 :
$functions = array(
'function1' => function($echo) { echo $echo; }
);
이것이 가능한가? 가장 좋은 대안은 무엇입니까?
몇 가지 옵션이 있습니다. 사용 create_function
:
$functions = array(
'function1' => create_function('$echo', 'echo $echo;')
);
함수의 이름을 문자열로 저장하기 만하면됩니다 (실제로 모든 작업 create_function
이 수행됨).
function do_echo($echo) {
echo $echo;
}
$functions = array(
'function1' => 'do_echo'
);
PHP 5.3을 사용하는 경우 익명 함수를 사용할 수 있습니다 .
$functions = array(
'function1' => function($echo) {
echo $echo;
}
);
이러한 모든 메서드는 callback
의사 유형 아래의 설명서에 나열되어 있습니다. 어느 쪽을 선택하든 함수를 호출하는 권장 방법은 call_user_func
또는 call_user_func_array
함수를 사용하는 것입니다.
call_user_func($functions['function1'], 'Hello world!');
PHP "5.3.0 익명 함수를 사용할 수있게 됨"이후 사용 예 :
이것은 old create_function
...를 사용하는 것보다 훨씬 빠릅니다 .
//store anonymous function in an array variable e.g. $a["my_func"]
$a = array(
"my_func" => function($param = "no parameter"){
echo "In my function. Parameter: ".$param;
}
);
//check if there is some function or method
if( is_callable( $a["my_func"] ) ) $a["my_func"]();
else echo "is not callable";
// OUTPUTS: "In my function. Parameter: no parameter"
echo "\n<br>"; //new line
if( is_callable( $a["my_func"] ) ) $a["my_func"]("Hi friend!");
else echo "is not callable";
// OUTPUTS: "In my function. Parameter: Hi friend!"
echo "\n<br>"; //new line
if( is_callable( $a["somethingElse"] ) ) $a["somethingElse"]("Something else!");
else echo "is not callable";
// OUTPUTS: "is not callable",(there is no function/method stored in $a["somethingElse"])
참고 문헌 :
익명 기능 : http://cz1.php.net/manual/en/functions.anonymous.php
콜 러블 테스트 : http://cz2.php.net/is_callable
Alex Barrett의 게시물에 대한 후속 조치를 위해 create_function ()은 실제로 함수를 호출하는 데 사용할 수있는 값을 반환합니다.
$function = create_function('$echo', 'echo $echo;' );
$function('hello world');
왜냐하면 내가 ...
Alex Barrett의 게시물을 확장합니다.
나는이 아이디어를 더 구체화하기 위해 노력할 것이다. 아마도 외부 정적 클래스와 같은 것으로, 아마도 '...'토큰을 사용하여 가변 길이 인수를 허용 할 것이다.
다음 예에서는 명확성을 위해 키워드 '배열'을 사용했지만 대괄호도 괜찮습니다. init 함수를 사용하는 레이아웃은 더 복잡한 코드의 구성을 보여주기위한 것입니다.
<?php
// works as per php 7.0.33
class pet {
private $constructors;
function __construct() {
$args = func_get_args();
$index = func_num_args()-1;
$this->init();
// Alex Barrett's suggested solution
// call_user_func($this->constructors[$index], $args);
// RibaldEddie's way works also
$this->constructors[$index]($args);
}
function init() {
$this->constructors = array(
function($args) { $this->__construct1($args[0]); },
function($args) { $this->__construct2($args[0], $args[1]); }
);
}
function __construct1($animal) {
echo 'Here is your new ' . $animal . '<br />';
}
function __construct2($firstName, $lastName) {
echo 'Name-<br />';
echo 'First: ' . $firstName . '<br />';
echo 'Last: ' . $lastName;
}
}
$t = new pet('Cat');
echo '<br />';
$d = new pet('Oscar', 'Wilding');
?>
좋아, 이제 한 줄로 다듬어 ...
function __construct() {
$this->{'__construct' . (func_num_args()-1)}(...func_get_args());
}
생성자뿐만 아니라 모든 함수를 오버로드하는 데 사용할 수 있습니다.
참고URL : https://stackoverflow.com/questions/1499862/can-you-store-a-function-in-a-php-array
'IT Share you' 카테고리의 다른 글
ASCII 값 목록을 파이썬에서 문자열로 어떻게 변환합니까? (0) | 2020.11.29 |
---|---|
파이썬 변수가 문자열인지 목록인지 어떻게 알 수 있습니까? (0) | 2020.11.29 |
'또는'조건이있는 MongoDB 쿼리 (0) | 2020.11.29 |
PHP를 사용하여 이전 URL을 얻는 방법 (0) | 2020.11.29 |
autosetuprebase 대 autosetupmerge (0) | 2020.11.29 |