PHP 可變函數

來源:互聯網
上載者:User

PHP 支援可變函數的概念。這意味著如果一個變數名後有圓括弧,PHP
將尋找與變數的值同名的函數,並且嘗試執行它。可變函數可以用來實現包括回呼函數,函數表在內的一些用途。

變數函數不能用於語言結構,例如 echo()

,print()

,unset()

,isset()

,empty()

,include()

,require()

以及類似的語句。需要使用自己的封裝函數來將這些結構用作變數函數。

 

Example #1 可變函數樣本

<?php

function 
foo
() {
    echo 
"In foo()<br />/n"
;
}

function 
bar
(
$arg 

''
) {
    echo 
"In bar(); argument was '
$arg
'.<br />/n"
;
}


// 使用 echo 的封裝函數

function 
echoit
(
$string
)
{
    echo 
$string
;
}


$func 

'foo'
;

$func
();        
// This calls foo()


$func 

'bar'
;

$func
(
'test'
);  
// This calls bar()


$func 

'echoit'
;

$func
(
'test'
);  
// This calls echoit()

?>

還可以利用可變函數的特性來調用一個對象的方法。

Example #2 可變方法範例

<?php

class 
Foo

{
    function 
Variable
()
    {
        
$name 

'Bar'
;
        
$this
->
$name
(); 
// This calls the Bar() method
    
}

    function 
Bar
()
    {
        echo 
"This is Bar"
;
    }
}


$foo 
= new 
Foo
();

$funcname 

"Variable"
;

$foo
->
$funcname
();   
// This calls $foo->Variable()


?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.