downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

내부 (내장) 함수> <반환값
Last updated: Fri, 24 Jul 2009

view this page in

가변 함수

PHP는 가변 함수에 대한 개념을 지원한다. 이 용어의 의미는 어떤 변수 뒤에 괄호가 따라온다면, PHP는 그 변수의 값을 갖는 함수를 찾아서 실행하려 할것이란 것이다. 이런 개념은 이기능 외에도 콜백과 함수 테이블 등등을 구현할수 있게 해준다.

가변 함수는 echo(), print(), unset(), isset(), empty(), include(), require()와 같은 언어 구조와 함께 작동하지 않을것이다. 래퍼 함수를 사용해서 이러한 구조를 가변 함수로 이용할 수 있습니다.

Example #1 가변 변수 사용예

<?php
function foo() {
    echo 
"foo() 안입니다.<br />\n";
}

function 
bar($arg '')
{
    echo 
"bar() 안입니다; 인수는 '$arg'입니다.<br />\n";
}

// echo를 감싸는 래퍼 함수입니다.
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // foo()를 호출합니다.

$func 'bar';
$func('test');  // bar()를 호출합니다.

$func 'echoit';
$func('test');  // echoit()을 호출합니다.
?>

객체 메쏘드도 가변 함수 구문으로 호출할 수 있습니다.

Example #2 가변 메쏘드 사용예

<?php
class Foo
{
    function 
Variable()
    {
        
$name 'Bar';
        
$this->$name(); // Bar() 메쏘드를 호출합니다.
    
}
    
    function 
Bar()
    {
        echo 
"This is Bar";
    }
}

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();  // $foo->Var()를 호출합니다.

?>

call_user_func(), variable variables, function_exists()섹션을 참고



내부 (내장) 함수> <반환값
Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes
가변 함수
boards at gmail dot com
23-Jan-2006 03:07
If you want to call a static function (PHP5) in a variable method:

Make an array of two entries where the 0th entry is the name of the class to be invoked ('self' and 'parent' work as well) and the 1st entry is the name of the function.  Basically, a 'callback' variable is either a string (the name of the function) or an array (0 => 'className', 1 => 'functionName').

Then, to call that function, you can use either call_user_func() or call_user_func_array().  Examples:

<?php
class A {

  protected
$a;
  protected
$c;

  function
__construct() {
   
$this->a = array('self', 'a');
   
$this->c = array('self', 'c');
  }

  static function
a($name, &$value) {
    echo
$name,' => ',$value++,"\n";
  }

  function
b($name, &$value) {
   
call_user_func_array($this->a, array($name, &$value));
  }

  static function
c($str) {
    echo
$str,"\n";
  }

  function
d() {
   
call_user_func_array($this->c, func_get_args());
  }

  function
e() {
   
call_user_func($this->c, func_get_arg(0));
  }

}

class
B extends A {

  function
__construct() {
   
$this->a = array('parent', 'a');
   
$this->c = array('self', 'c');
  }

  static function
c() {
   
print_r(func_get_args());
  }

  function
d() {
   
call_user_func_array($this->c, func_get_args());
  }

  function
e() {
   
call_user_func($this->c, func_get_args());
  }

}

$a =& new A;
$b =& new B;
$i = 0;

A::a('index', $i);
$a->b('index', $i);

$a->c('string');
$a->d('string');
$a->e('string');

# etc.
?>
Storm
04-May-2005 12:34
This can quite useful for a dynamic database class:

(Note: This just a simplified section)

<?php
class db {

    private
$host = 'localhost';
    private
$user = 'username';
    private
$pass = 'password';
    private
$type = 'mysqli';
   
    public
$lid = 0;

   
// Connection function
   
function connect() {
       
$connect = $this->type.'_connect';
           
        if (!
$this->lid = $connect($this->host, $this->user, $this->pass)) {
            die(
'Unable to connect.');
        }
 }
}
$db  = new db;
$db->connect();
?>

Much easier than having multiple database classes or even extending a base class.
ian at NO_SPAM dot verteron dot net
21-Dec-2002 12:33
A good method to pass around variables containing function names within some class is to use the same method as the developers use in preg_replace_callback - with arrays containing an instance of the class and the function name itself.

function call_within_an_object($fun)
{
  if(is_array($fun))
  {
    /* call a function within an object */
    $fun[0]->{$fun[1]}();
  }
  else
  {
    /* call some other function */
    $fun();
  }
}

function some_other_fun()
{
  /* code */
}

class x
{
  function fun($value)
  {
    /* some code */
  }
}

$x = new x();

/* the following line calls $x->fun() */
call_within_an_object(Array($x, 'fun'));

/* the following line calls some_other_fun() */
call_within_an_object('some_other_fun');
madeinlisboa at yahoo dot com
05-Sep-2002 09:14
Finally, a very easy way to call a variable method in a class:

Example of a class:

class Print() {
    var $mPrintFunction;

    function Print($where_to) {
        $this->mPrintFunction = "PrintTo$where_to";
    }

    function PrintToScreen($content) {
        echo $content;
    }

    function PrintToFile($content) {
        fputs ($file, $contents);
    }

.. .. ..

    // first, function name is parsed, then function is called
    $this->{$this->mPrintFunction}("something to print");
}
msmith at pmcc dot com
03-May-2002 08:49
Try the call_user_func() function.  I find it's a bit simpler to implement, and at very least makes your code a bit more readable... much more readable and simpler to research for someone who isn't familiar with this construct.
anpatel at NOSPAM_cbu dot edu
18-Mar-2002 02:11
Yes interpolation can be very tricky. I suggest that you always use parenthesis, or curly brackets(whichever applies) to make your expression clear.

Dont ever depend on a language's expression parse preference order.
retro at enx dot org
14-Jan-2002 12:18
Another way to have php parse a variable within an object as a function is to simply set a temporary variable to its value. For example:

$obj->myfunction = "foo";
$x = $obj->myfunction;
$x(); // calls the function named "foo"

내부 (내장) 함수> <반환값
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites