Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php可变函数使用分析

php可变函数使用分析

伊谢尔伦
伊谢尔伦asal
2017-06-26 09:28:261219semak imbas

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。 

变量函数不能用于语言结构,例如 echo() ,print() ,unset() ,isset() ,empty() ,include() ,require() 以及类似的语句。需要使用自己的包装函数来将这些结构用作变量函数。 
Example #1 可变函数示例 

<?php
function  foo () {
    echo  "In foo()<br />/n" ;
}
function  bar ( $arg  =  &#39;&#39; ) {
    echo  "In bar(); argument was &#39; $arg &#39;.<br />/n" ;
}
// 使用 echo 的包装函数
function  echoit ( $string )
{
    echo  $string ;
}
$func  =  &#39;foo&#39; ;
$func ();         // This calls foo()
$func  =  &#39;bar&#39; ;
$func ( &#39;test&#39; );   // This calls bar()
$func  =  &#39;echoit&#39; ;
$func ( &#39;test&#39; );   // This calls echoit()
?>

还可以利用可变函数的特性来调用一个对象的方法。


Example #2 可变方法范例 

<?php
class  Foo
{
    function  Variable ()
    {
         $name  =  &#39;Bar&#39; ;
         $this -> $name ();  // This calls the Bar() method
     }
    function  Bar ()
    {
        echo  "This is Bar" ;
    }
}
$foo  = new  Foo ();
$funcname  =  "Variable" ;
$foo -> $funcname ();    // This calls $foo->Variable()
?>

Atas ialah kandungan terperinci php可变函数使用分析. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn