A-A+

php 可变函数使用小结

2019年02月15日 我爱编程 暂无评论

ke'bia可变函数

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。

变量函数不能用于语言结构,例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及类似的语句。需要使用自己的包装函数来将这些结构用作变量函数。

先将我的伪代码写上。

  1. protected $model;
  2. public function __construct(Category $category)
  3. {
  4.  $this->model = $category;
  5. }
  6. public function getLists($request$isPage = 'get'$order = 'created_at'$sort = 'desc')
  7. {
  8.  return $this->model->orderBy($order$sort)->$isPage();
  9. }

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

什么是可变函数?

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

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

示例:

  1. <!--?php
  2. function foo() {
  3.  echo "In foo()<br /-->\n";
  4. }
  5. function bar($arg = '') {
  6.  echo "In bar(); argument was '$arg'.<br>\n";
  7. }
  8. $func = 'foo';
  9. $func();  // 执行 foo(); 命令行中输出:In foo()<br>
  10. $func = 'bar';
  11. $func('test'); // 执行 bar();命令行中输出:In bar(); argument was 'test'.<br>

可变函数的语法来调用一个对象的方法。

  1. <!--?phpclass Foo
  2. {
  3.  function Variable()
  4.  {
  5.   $name = 'Bar';
  6.   $this--->$name(); // This calls the Bar() method
  7.  }
  8.  function Bar()
  9.  {
  10.   echo "This is Bar";
  11.  }
  12. }
  13. $foo = new Foo();
  14. $funcname = "Variable";
  15. $foo->$funcname(); // This calls $foo->Variable()
  16. // 命令行执行输出: This is Bar

当调用静态方法时,函数调用要比静态属性优先。Variable 方法和静态属性示例。

  1. <!--?php
  2. class Foo
  3. {
  4.  static $variable = 'static property';
  5.  static function Variable()
  6.  {
  7.   echo 'Method Variable called';
  8.  } //phpfensi.com
  9. }
  10. echo Foo::$variable// This prints 'static property'. It does need a $variable in this scope.
  11. $variable = "Variable";
  12. Foo::$variable(); // This calls $foo--->Variable() reading $variable in this scope.

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录