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 = '') {
    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

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
1
粉丝
1
喜欢
1
收藏
0
排名:1318
访问:2991
私信
所有博文
社区赞助商