PHP 支援可變函數的概念。這意味著如果一個變數名後面有圓括號,PHP 將尋找與變數的值同名的函數,並且嘗試執行它。本文重點介紹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();
}$this->model->orderBy($order, $sort)->get(); 是這樣的,我也沒見過使用變數來替換get() 的。在實際運行中,程式正常執行。隨後在論壇中詢問這種寫法。接下來就要引入一個概念,《可變函數》。
什麼是可變函數?
PHP 支援可變函數的概念。這意味著如果一個變數名後面有圓括號,PHP 將尋找與變數的值同名的函數,並且嘗試執行它。 了解了這個概念以後那麼上述程式就可以講的通了。 $isPage 在程式運行中,替換為 get, 而 $isPage 後面有一個圓括號,那麼程式就會尋找同名函數。進而繼續執行。 範例:<?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 /><?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()
// 命令行执行输出: This is Bar<?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中文網其他相關文章!