转载

PHP 可变函数

php 可变函数

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

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

Example #1 可变函数示例

  1. <?php 
  2. function foo () { 
  3. echo "In foo()<br />/n" ; 
  4. } 
  5.  
  6. function bar ( $arg = '' ) { 
  7. echo "In bar(); argument was ' $arg '.<br />/n" ; 
  8. } 
  9.  
  10. // 使用 echo 的包装函数 
  11. function echoit ( $string ) 
  12. { 
  13. echo $string ; 
  14. } 
  15.  
  16. $func = 'foo' ; 
  17. $func (); // This calls foo() 
  18.  
  19. $func = 'bar' ; 
  20. $func ( 'test' ); // This calls bar() 
  21.  
  22. $func = 'echoit' ; 
  23. $func ( 'test' ); // This calls echoit() 
  24. ?>  

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

Example #2 可变方法范例

  1. <?php 
  2. class Foo 
  3. { 
  4. function Variable () 
  5. { 
  6. $name = 'Bar' ; 
  7. $this -> $name (); // This calls the Bar() method 
  8. } 
  9.  
  10. function Bar () 
  11. { 
  12. echo "This is Bar" ; 
  13. } 
  14. } 
  15.  
  16. $foo = new Foo (); 
  17. $funcname = "Variable" ; 
  18. $foo -> $funcname (); // This calls $foo->Variable() 
  19.  
  20. ?>  

当调用静态方法时,函数调用要比静态属性优先:

Example #3 Variable 方法和静态属性示例:

  1. <?php 
  2. class Foo 
  3. { 
  4. static $variable = 'static property' ; 
  5. static function Variable () 
  6. { 
  7. echo 'Method Variable called' ; 
  8. } 
  9. } 
  10.  
  11. echo Foo :: $variable ; // This prints 'static property'. It does need a $variable in this scope. 
  12. $variable = "Variable" ; 
  13. Foo :: $variable (); // This calls $foo->Variable() reading $variable in this scope. 
  14.  
  15. ?> 
正文到此结束
Loading...