先將個人僞代碼寫上。php
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()
的。在實際運行中,程序正常執行。隨後在論壇中詢問這種寫法。接下來就要引入一個概念,《可變函數》。函數
PHP 支持可變函數的概念。這意味着若是一個變量名後有圓括號,PHP 將尋找與變量的值同名的函數,而且嘗試執行它。
瞭解了這個概念之後那麼上述程序就能夠講的通了。$isPage
在程序運行中,替換爲 get
, 而 $isPage
後有一個圓括號,那麼程序就會尋找同名函數。進而繼續執行。this
示例:
<?php function foo() { echo "In foo()<br />\n"; } function bar($arg = '') { echo "In bar(); argument was '$arg'.<br />\n"; } $func = 'foo'; $func(); // 執行 foo(); 命令行中輸出:In foo()<br /> $func = 'bar'; $func('test'); // 執行 bar();命令行中輸出:In bar(); argument was 'test'.<br />
可變函數的語法來調用一個對象的方法。
<?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() // 命令行執行輸出: This is Bar
當調用靜態方法時,函數調用要比靜態屬性優先。Variable 方法和靜態屬性示例。
<?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 可變函數
轉載地址 lost in you .net