可變函數
PHP 支持可變函數的概念。這意味著如果一個變量名后有圓括號,PHP 將尋找與變量的值同名的函數,并且嘗試執(zhí)行它??勺兒瘮悼梢杂脕韺崿F包括回調函數,函數表在內的一些用途。
變量函數不能用于語言結構,例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及類似的語句。需要使用自己的包裝函數來將這些結構用作變量函數。
先將我的偽代碼寫上。
protected $model;
public function __construct(Category $category)
{
$this->model = $category;
}
public function getLists($request, $isPage = 'get', $order = 'created_at', $sort = 'desc')
{
return $this->model->orderBy($order, $sort)->$isPage();
}
在 getLists 中,有一個 $isPage 的參數。本意是傳入 get 就是獲取全部數據,paginate 就是分頁。寫完以后覺得哪里不對。在我們平常的寫法中,查找全部數據 $this->model->orderBy($order, $sort)->get();
是這樣的,我也未見過使用變量來替換 get() 的。在實際運行中,程序正常執(zhí)行。隨后在論壇中詢問這種寫法。接下來就要引入一個概念,《可變函數》。
什么是可變函數?
PHP 支持可變函數的概念。這意味著如果一個變量名后有圓括號,PHP 將尋找與變量的值同名的函數,并且嘗試執(zhí)行它。
了解了這個概念以后那么上述程序就可以講的通了。$isPage 在程序運行中,替換為 get, 而 $isPage 后有一個圓括號,那么程序就會尋找同名函數。進而繼續(xù)執(zhí)行。
示例:
?php
function foo() {
echo "In foo()br />\n";
}
function bar($arg = '') {
echo "In bar(); argument was '$arg'.br />\n";
}
$func = 'foo';
$func(); // 執(zhí)行 foo(); 命令行中輸出:In foo()br />
$func = 'bar';
$func('test'); // 執(zhí)行 bar();命令行中輸出:In bar(); argument was 'test'.br />
可變函數的語法來調用一個對象的方法。
?phpclass 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()
// 命令行執(zhí)行輸出: This is Bar
當調用靜態(tài)方法時,函數調用要比靜態(tài)屬性優(yōu)先。Variable 方法和靜態(tài)屬性示例。
?php
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}
echo Foo::$variable; // This prints 'static property'. 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可變長參數處理函數詳解
- php定義參數數量可變的函數用法實例
- PHP可變函數的使用詳解
- JS與PHP向函數傳遞可變參數的區(qū)別實例代碼
- php 獲取可變函數參數的函數