php 自訂函數大全

來源:互聯網
上載者:User

標籤:

 

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, "actionWithArgs"), 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

php 自訂函數大全

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.