development

PHP call_user_func 대 호출 함수

big-blog 2020. 9. 16. 08:07
반응형

PHP call_user_func 대 호출 함수


나는 이것에 대한 매우 쉬운 설명이 있다고 확신합니다. 이것의 차이점은 무엇입니까?

function barber($type){
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");

... 그리고 이것 (그리고 이점은 무엇입니까?) :

function barber($type){
    echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');

알면 항상 실제 함수 이름을 사용하십시오.

call_user_func 이름을 미리 알 수없는 함수를 호출하기위한 것이지만 프로그램이 런타임에 함수를 조회해야하기 때문에 훨씬 덜 효율적입니다.


이 방법으로 변수 함수 이름을 호출 할 수 있지만 :

function printIt($str) { print($str); }

$funcname = 'printIt';
$funcname('Hello world!');

당신이 얼마나 많은 논쟁을 전달하고 있는지 모르는 경우가 있습니다. 다음을 고려하세요:

function someFunc() {
  $args = func_get_args();
  // do something
}

call_user_func_array('someFunc',array('one','two','three'));

또한 각각 정적 및 객체 메서드를 호출하는 데 편리합니다.

call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);

call_user_func당신이 좋아하는 일을 할 수 있도록 옵션이 있습니다 :

$dynamicFunctionName = "barber";

call_user_func($dynamicFunctionName, 'mushroom');

를 Where dynamicFunctionName문자열은 더 흥미 진진하고 런타임에 생성 될 수 있습니다. 필요하지 않으면 call_user_func를 사용하면 안됩니다.


사전에 이름을 모르는 함수를 호출하는 데 유용하다고 생각합니다.

switch($value):
{
  case 7:
  $func = 'run';
  break;
  default:
  $func = 'stop';
  break;
}

call_user_func($func, 'stuff');

코어 파일을 편집하는 것은 좋은 옵션이 아니기 때문에 주로 "사용자"함수 (플러그인과 같은)를 호출하는 데 사용되었다고 생각하기 때문에 그런 함수를 호출하는 이점은 없습니다. 다음은 Wordpress에서 사용하는 더러운 예입니다.

<?php
/* 
* my_plugin.php
*/

function myLocation($content){
  return str_replace('@', 'world', $content);
}

function myName($content){
  return $content."Tasikmalaya";
}

add_filter('the_content', 'myLocation');
add_filter('the_content', 'myName');

?>

...

<?php
/*
* core.php
* read only
*/

$content = "hello @ my name is ";
$listFunc = array();

// store user function to array (in my_plugin.php)
function add_filter($fName, $funct)
{
  $listFunc[$fName]= $funct;
}

// execute list user defined function
function apply_filter($funct, $content)
{
  global $listFunc;

  if(isset($listFunc))
  {
    foreach($listFunc as $key => $value)
    {
      if($key == $funct)
      {
        $content = call_user_func($listFunc[$key], $content);
      }
    }
  }
  return $content;
}

function the_content()
{
  $content = apply_filter('the_content', $content);
  echo $content;
}

?>

....

<?php
require_once("core.php");
require_once("my_plugin.php");

the_content(); // hello world my name is Tasikmalaya
?>

산출

hello world my name is Tasikmalaya

PHP 7을 사용하면 어디에서나 더 멋진 가변 함수 구문을 사용할 수 있습니다. 정적 / 인스턴스 함수와 함께 작동하며 매개 변수 배열을 사용할 수 있습니다. https://trowski.com/2015/06/20/php-callable-paradox 에서 자세한 정보

$ret = $callable(...$params);

첫 번째 예에서는 문자열 인 함수 이름을 사용하고 있습니다. 그것은 외부에서 오거나 즉석에서 결정될 수 있습니다. 즉, 코드 생성 시점에 어떤 기능을 실행해야하는지 알 수 없습니다.


When using namespaces, call_user_func() is the only way to run a function you don't know the name of beforehand, for example:

$function = '\Utilities\SearchTools::getCurrency';
call_user_func($function,'USA');

If all your functions were in the same namespace, then it wouldn't be such an issue, as you could use something like this:

$function = 'getCurrency';
$function('USA');

Edit: Following @Jannis saying that I'm wrong I did a little more testing, and wasn't having much luck:

<?php
namespace Foo {

    class Bar {
        public static function getBar() {
            return 'Bar';
        }
    }
    echo "<h1>Bar: ".\Foo\Bar::getBar()."</h1>";
    // outputs 'Bar: Bar'
    $function = '\Foo\Bar::getBar';
    echo "<h1>Bar: ".$function()."</h1>";
    // outputs 'Fatal error: Call to undefined function \Foo\Bar::getBar()'
    $function = '\Foo\Bar\getBar';
    echo "<h1>Bar: ".$function()."</h1>";
    // outputs 'Fatal error: Call to undefined function \foo\Bar\getBar()'
}

You can see the output results here: https://3v4l.org/iBERh it seems the second method works for PHP 7 onwards, but not PHP 5.6.

참고URL : https://stackoverflow.com/questions/1596221/php-call-user-func-vs-just-calling-function

반응형