关于php 可变函数的一些示例

怪我咯
Lepaskan: 2023-03-11 16:44:01
asal
1146 orang telah melayarinya

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()
?>
Salin selepas log masuk

也可以用可变函数的语法来调用一个对象的方法。

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()

?>
Salin selepas log masuk

当调用静态方法时,函数调用要比静态属性优先:

Example #3 Variable 方法和静态属性示例

<?php
class  Foo
{
    static  $variable  =  &#39;static property&#39; ;
    static function  Variable ()
    {
        echo  &#39;Method Variable called&#39; ;
    }
}

echo  Foo :: $variable ;  // This prints &#39;static property&#39;. It does need a $variable in this scope.
$variable  =  "Variable" ;
Foo :: $variable ();   // This calls $foo->Variable() reading $variable in this scope.

?>
Salin selepas log masuk

Atas ialah kandungan terperinci 关于php 可变函数的一些示例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
php
sumber:php.cn
Kenyataan Laman Web ini
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
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!