首页  >  文章  >  后端开发  >  php的可变函数

php的可变函数

不言
不言原创
2018-07-06 17:37:062099浏览

这篇文章主要介绍了关于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();
    }

getLists 中,有一个 $isPage 的参数。本意是传入 get 就是获取全部数据,paginate 就是分页。写完以后觉得哪里不对。在我们平常的写法中,查找全部数据 $this->model->orderBy($order, $sort)->get();  是这样的,我也未见过使用变量来替换 get()  的。在实际运行中,程序正常执行。随后在论坛中询问这种写法。接下来就要引入一个概念,《可变函数》。

什么是可变函数?

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。

了解了这个概念以后那么上述程序就可以讲的通了。$isPage 在程序运行中,替换为 get, 而 $isPage 后有一个圆括号,那么程序就会寻找同名函数。进而继续执行。

示例:
<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = &#39;&#39;) {
    echo "In bar(); argument was &#39;$arg&#39;.<br />\n";
}
$func = &#39;foo&#39;;
$func();        //  执行 foo(); 命令行中输出:In foo()<br />

$func = &#39;bar&#39;;
$func(&#39;test&#39;);   // 执行 bar();命令行中输出:In bar(); argument was &#39;test&#39;.<br />
可变函数的语法来调用一个对象的方法。
<?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()

// 命令行执行输出: This is Bar
当调用静态方法时,函数调用要比静态属性优先。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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn