加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php 自定义函数大全

发布时间:2020-12-13 21:21:34 所属栏目:PHP教程 来源:网络整理
导读:? 1. call_user_func和call_user_func_array 以上两个函数以不同的参数形式调用函数。见如下示例: ?php class demo { public static function action1() { echo "This is demo::action1.br"; } public function action2() { echo "This is demo::action2.br

?

1. call_user_func和call_user_func_array

以上两个函数以不同的参数形式调用函数。见如下示例:
<?php

class demo
{
public static function action1()
{
echo "This is demo::action1.<br>";
}

public function action2()
{
echo "This is demo::action2.<br>";
}

public function actionWithArgs($arg1,$arg2)
{
echo 'This is demo::actionWithArgs with ($arg1 = ' . $arg1 . ' and $arg2 = ' . $arg2 . ").<br>";
}
}

$demo = new demo();
call_user_func(array("demo","action1"));
call_user_func(array($demo,"action2"));
call_user_func(array($demo,"actionWithArgs"),"hello","world");
call_user_func_array(array($demo,array("hello2","world2"));


运行结果如下:

This is demo::action1.
This is demo::action2.
This is demo::actionWithArgs with ($arg1 = hello and $arg2 = world).
This is demo::actionWithArgs with ($arg1 = hello2 and $arg2 = world2).

2. func_get_args、func_num_args和func_get_args

这三个函数的共同特征是都很自定义函数参数相关,而且均只能在函数内使用,比较适用于可变参数的自定义函数。他们的函数原型和简要说明如下:
int func_num_args (void) 获取当前函数的参数数量。
array func_get_args (void) 以数组的形式返回当前函数的所有参数。
mixed func_get_arg (int $arg_num) 返回当前函数指定位置的参数,其中0表示第一个参数。

<?php
function demoA()
{
$numOfArgs = func_num_args();
$args = func_get_args();
echo "The number of args in demoA is " . $numOfArgs . "<br>";
for ($i = 0; $i < $numOfArgs; $i++) {
echo "The {$i}th arg is " . func_get_arg($i) . "<br>";
}
echo "-------------------------------------------<br>";
foreach ($args as $arg) {
echo "$arg<br>";
}
}

demoA('hello','world','123456');

运行结果如下:

The number of args in demoA is 3
The 0th arg is hello
The 1th arg is world
The 2th arg is 123456
-------------------------------------------
hello
world
123456

3. register_shutdown_function

函数原型和简要说明如下:

void register_shutdown_function (callable $callback [,mixed $parameter [,mixed $... ]]) 在脚本结束之前或者是中途调用exit时调用改注册的函数。另外,如果注册多个函数,那么他们将会按照注册时的顺序被依次执行,如果其中某个回调函数内部调用了exit(),那么脚本将立刻退出,剩余的回调均不会被执行。

<?php
function myShutdown($arg1,$arg2)
{
echo '$arg1 = ' . $arg1 . ',$arg2 = ' . $arg2 . "<br>";
}

if (function_exists('myShutdown')) {
print "myShutdown function exists now.<br>";
}

register_shutdown_function('myShutdown','Hello','World');
print "This test is executed.<br>";
exit();
echo "This comments cannot be output.<br>";

运行结果如下:

myShutdown function exists now.
This test is executed.
$arg1 = Hello,$arg2 = World

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读