關於php 可變函數的一些範例

怪我咯
發布: 2023-03-11 16:44:01
原創
1123 人瀏覽過

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

?>
登入後複製

當呼叫靜態方法時,函數呼叫要比靜態屬性優先:

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.

?>
登入後複製

以上是關於php 可變函數的一些範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!