php学习之道:call_user_func跟call_user_func_array的用法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php学习之道:call_user_func跟call_user_func_array的用法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2043字,纯文字阅读大概需要3分钟。
内容图文
php学习之道:call_user_func和call_user_func_array的用法call_user_func ( callback $function [, mixed $parameter [, mixed $... ]] )
调用第一个参数所提供的用户自定义的函数。
返回值:返回调用函数的结果,或FALSE。
example :
- function eat($fruit) //参数可以为多个
- {
- echo "You want to eat $fruit, no problem";
- }
- call_user_func('eat', "apple"); //print: You want to eat apple, no problem;
- call_user_func('eat', "orange"); //print: You want to eat orange,no problem;
- ?>
调用类的内部方法:
- class myclass {
- function say_hello($name)
- {
- echo "Hello!$name";
- }
- }
- $classname = "myclass";
- //调用类内部的函数需要使用数组方式 array(类名,方法名)
- call_user_func(array($classname, 'say_hello'), 'dain_sun');
- //print Hello! dain_sun
- ?>
call_user_func_array 函数和 call_user_func 很相似,只是 使 用了数组 的传递参数形式,让参数的结构更清晰:
call_user_func_array ( callback $function , array $param_arr )
调用用户定义的函数,参数为数组形式。
返回值:返回调用函数的结果,或FALSE。
- function debug($var, $val)
- {
- echo "variable: $var
value: $val
"; - echo "
"; - }
- $host = $_SERVER["SERVER_NAME"];
- $file = $_SERVER["PHP_SELF"];
- call_user_func_array('debug', array("host", $host));
- call_user_func_array('debug', array("file", $file));
- ?>
调用类的内部方法和 call_user_func 函数的调用方式一样,都是使用了数组的形式来调用。
exmaple:
- class test
- {
- function debug($var, $val)
- {
- echo "variable: $var
value: $val
"; - echo "
"; - }
- }
- $host = $_SERVER["SERVER_NAME"];
- $file = $_SERVER["PHP_SELF"];
- call_user_func_array(array('test', 'debug'), array("host", $host));
- call_user_func_array(array('test', 'debug'), array("file", $file));
- ?>
注:call_user_func 函数和call_user_func_array函数都支持引用。
- function increment(&$var)
- {
- $var++;
- }
- $a = 0;
- call_user_func('increment', $a);
- echo $a; // 0
- call_user_func_array('increment', array(&$a)); // You can use this instead
- echo $a; // 1
- ?>
内容总结
以上是互联网集市为您收集整理的php学习之道:call_user_func跟call_user_func_array的用法全部内容,希望文章能够帮你解决php学习之道:call_user_func跟call_user_func_array的用法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。