Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

Глава 17. Функции

Функции, определяемые пользователем

Приведем пример синтаксиса, используемого для описания функций:

Пример 17-1. Псевдокод для демонстрации использования функций

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo
"Example function.\n";
    return
$retval;
}
?>

Внутри функции можно использовать любой корректный PHP-код, в том числе другие функции и даже объявления классов.

В PHP 3 функции должны были быть определены прежде, чем они будут использованы. Начиная с PHP 4 такого ограничения нет, исключая тот случай, когда функции определяются условно, как это показано в двух последующих примерах.

В случае, когда функция определяется в зависимости от какого-либо условия, например, как это показано в двух приведенных ниже примерах, обработка описания функции должна предшествовать ее вызову.

Пример 17-2. Функции, зависящие от условий

<?php

$makefoo
= true;

/* Мы не можем вызвать функцию foo() в этом месте,
   поскольку она еще не определена, но мы можем
   обратиться к bar() */

bar();

if (
$makefoo) {
  function
foo()
  {
    echo
"I don't exist until program execution reaches me.\n";
  }
}

/* Теперь мы благополучно можем вызывать foo(),
   поскольку $makefoo была интерпретирована как true */

if ($makefoo) foo();

function
bar()
{
  echo
"I exist immediately upon program start.\n";
}

?>

Пример 17-3. Вложенные функции

<?php
function foo()
{
  function
bar()
  {
    echo
"I don't exist until foo() is called.\n";
  }
}

/* Мы пока не можем обратиться к bar(),
   поскольку она еще не определена. */

foo();

/* Теперь мы можем вызвать функцию bar(),
   обработка foo() сделала ее доступной. */

bar();

?>

PHP не поддерживает перегрузку функции, также отсутствует возможность переопределить или удалить объявленную ранее функцию.

Замечание: Имена функций регистронезависимы, тем не менее, более предпочтительно вызывать функции так, как они были объявлены.

PHP 3 не поддерживает переменное количество аргументов функции, хотя поддержка значений по умолчанию для аргументов присутствует (смотрите раздел Значения аргументов по умолчанию). Начиная с 4-й версии PHP поддерживает и то, и другое: смотрите раздел Списки аргументов переменной длины и описания функций func_num_args(), func_get_arg(), и func_get_args() для более детальной информации.



Аргументы функции> <include_once
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
Функции
SID TRIVEDI
25-Oct-2007 11:56
<?php
/*
Example of a simple arithmatic function returning mutliple values of variables retrning outside of a function by means of an array.
*/

$a = null;// variable definition and initial value assignment.
$b =null; // variable definition and initial value assignment.
function arithmatic($a,$b)// Here $a and $b as function argument - operands (to be operated upon.
{
global
$sum; // global makes variable $sum available outside the function.
global $array; // global makes variable $sum available outside the function.
$sum = $a + $b;
$dif = $a - $b;
$mul = $a * $b;
$div = bcdiv($a,$b,2);// division precision with 2 decimal points.
$array = array($a, $b, $sum, $dif, $mul, $div);
return
$array;
}
arithmatic(11,5); // function call by values of $a and $b
list($a, $b, $sum, $dif, $mul, $div) = $array;
echo
"$a plus $b equals to $sum.\n<br>";
echo
"$a minus $b equals to $dif.\n<br>";
echo
"$a multiplied by $b equals to $mul.\n<br>";
echo
"$a divided by $b equals to $div.\n<br>";
/*
This generates following output :
11 plus 5 equals to 16.
11 minus 5 equals to 6.
11 multiplied by 5 equals to 55.
11 divided by 5 equals to 2.20.
*/
?>
email at fake dot com
31-Aug-2007 10:06
You can set variable DEFUALT values for a function in the (). These will be over-written by any input values (or non values).

function defualt_values_test ($a = 123, $b = 456){
   echo "a = ".$a."<br/>";
   echo "b = ".$b."<br/>";
   echo "<br/>";
}

defualt_values_test();       // uses values set in 'header'
defualt_values_test('overwritten',987654321);       // uses these values
defualt_values_test($non_existant,"var A has to be overwritten.");        // you can only use this for the last vars.

OUTPUTS:
----------

a = 123
b = 456

a = overwritten
b = 987654321

a =
b = var A has to be overwritten.
Gautam
23-Aug-2007 02:57
<?php
/*
User Defined Functions

function function_name($arg_1, $arg_2, ...,  $arg_n)
{
    code_line1;
    code_line2;
    code_line3;
    return ($value); //stops execution of the function and returns its argument as the value at the point where the function was called.
}
One may have more than one return()statements in a function.
*/

   
$text= 'This Line is Bold and Italics.';
    function
makebold_n_italics($text)
    {
       
$text = "<i><b>$text</i></b>";
        return(
$text); //the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call in print command
   
}
    print(
"This Line is not Bold.<br>\n");
    print(
"This Line is not Italics.<br>\n");
    echo
makebold_n_italics("$text") ,"--->", 'It prints the returned value of variable $text when function is called.'."<br>\n";
    echo
"$text", '---> prints the original value of  variable $text.'."<br>\n"; // prints the original value of $text
   
$thanks='Thanks to Zeev Suraski and Andi Gutmans !!!';
   
$text=$thanks;
    echo
makebold_n_italics("$text");

/*
Above codes produces output in a browser as under:

This Line is not Bold.
This Line is not Italics.
This Line is Bold and Italics.--->It prints the returned value of variable $text when function is called.
This Line is Bold and Italics.---> prints the original value of variable $text.
Thanks to Zeev Suraski and Andi Gutmans !!!
*/
?>
Raz
31-Jul-2007 03:56
You can use variables instead of original function name, calling user defined function depend on the function name; therefore if we set a variable to a string exactly like function name, it will call the function.
Example:
<?PHP
/* Define Function */
function plus($a, $b){
$c=$a+$b;
echo
"$a+$b=$b </br>";
}

//calling fucntion
plus(2,3);

//setting variable function
$vars ='plus';
$vars(2,3); //same as plus(2,3);

// Construct the same out put:
# 2+3=5
# 2+3=5

?>
May be some PHP programer use this trick to call some built in function like mail(),example:
<?php
//....
$some_vars=chr(109).chr(97).chr(105).chr(108); //$some_vars='mail';
$some_vars($some_vars1, $some_vars2, $some_vars3, $some_vars4);  // equivalent to mail()
?>
The above 2 line is a mail function that can be used in the script, it's possible that $some_vars3 that's a message will contain every submitted data in your script that sent to $some_vars1 (to some one email  address),

so be careful to see all source code for any PHP scripts before using it, because the most PHP Programs right now may use MySQL database, and during installation or running the script its possible that your script contain the above 2 lines (of course with some modification).
wassermann at REMOVEucdavis dot edu
19-Jul-2007 06:32
deek at none dot net,

The explanation of why your example does what it does is not quite right.

function ChangeString(&$SuplyedString)
 {
 $SuplyedString = "BBB";
 };

ChangeString($AAA='AAA');
print $AAA;
exit;

The assignment does, in fact, get executed before the function call.  The reason that this prints 'AAA' is because '=' is an operator that returns the value that it assigned.  In this case, the value 'AAA' is assigned to the variable $AAA, and the assignment expression returns a value of 'AAA'.  It is this returned value that gets passed as an argument to the function, and this returned value is unconnected to the variable $AAA.

$AAA = 'AAA';
ChangeString($AAA);
print $AAA;
exit;

In this case, a reference to the variable is being passed.  Hope this helps...
deek at none dot net
03-Jul-2007 09:43
Small Note:

While passing variables by reference ...

This first example does <NOT> work as expected....

function ChangeString(&$SuplyedString)
 {
 $SuplyedString = "BBB";
 };

ChangeString($AAA='AAA');
print $AAA;
exit;

This will print 'AAA' ... and not the referenced value of 'BBB' as expected. It seems that the = sign is interpreted after the function is executed and not before as one might think?

Thus the fix is simple but more typing...

Same function but use ...

$AAA = 'AAA';
ChangeString($AAA);
print $AAA;
exit;

This will now print 'BBB' as it should.

Hope it saves you some debug time...
pinkgothic at gmail dot com
02-May-2007 02:48
Be careful: Whilst you can enter any amount of excess parameters for run-time functions, PHP's in-built functions are capped, and will FAIL if you attempt to exceed this cap. For example:

<?php
  implode
(",",$arr); // (for reference)
 
implode(",",$arr,$set_var); // WARNING: Wrong parameter count
 
implode(",",$arr,$unset_var); // WARNING: Wrong parameter count
 
implode(",",$arr,NULL); // WARNING: Wrong parameter count
 
myimplode(",",$arr,$set_var); // Not an issue
?>

The function calls that cause a 'Wrong parameter count' warning return NULL.

I noticed this when trying to use $callback(...) with the values $callback = "imagecopyresampled"; and $callback = "imagecopy"; which seemed like a good idea at the time - the two functions have almost identical parameter lists, but imagecopy() would fail because it has two parameters less.
badguy at badguy dot nl
24-Nov-2006 01:22
I would like to add that the exception on what is explained on undefining and redefining functions is not noted here due to runkit being part of the PECL library. Which is as-of-yet (PHP 5.2) not a standard part of PHP and they need to be installed seperately. Please check http://www.php.net/manual/en/ref.runkit.php for more information on runkit and it's applications.
leblanc at tamu dot edu
03-Nov-2006 08:31
manual says:
>nor is it possible to undefine or redefine previously-declared functions.

you can undefine or redefine a function.. or so it says.. using
runkit_function_remove
runkit_function_redefine
maybe to implement perl's Memoize module
tom pittlik
04-Feb-2006 11:53
This is a way of formatting different strings with different mandatory functions and is especially useful when processing form data or outputting database fields using structured configuration files:

<?

function format_string($string,$functions)
{
    $funcs = explode(",",$functions);

    foreach ($funcs as $func)
    {
        if (function_exists($func)) $string = $func($string);
    }

    return $string;
}

echo format_string("  <b>   this is a test         </b>","strip_tags,strtoupper,trim");
// outputs "THIS IS A TEST"

?>
gnirts dot REMOVE_THIS at HATE_SPAM dot gmail dot com
04-Jan-2006 10:11
If you want to validate that a string could be a valid function name, watch out. preg_match() matches anywhere inside the test string, so strings like 'foo#' and '    bar' will pass with the regex that they give ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)

The solution is to use anchors in the regex (^ and $) and check the offset of the match (using PREG_OFFSET_CAPTURE).

<?

function is_valid_function_name( $function_name_to_test )
{
    $number_of_matches = preg_match( '<^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$>'
                                       , $function_name_to_test
                                       , $match_offset_array
                                       , PREG_OFFSET_CAPTURE );

    if( $number_of_matches === false )
    {
        trigger_error( 'Error with preg_match' , E_USER_WARNING );
    }

    if( $match_offset_array[0][1] !== 0 || $number_of_matches !== 1 )
    {
        return false;
    }
    else
    {
        return true;
    }
}

?>
p at onion dot whitefyre dot com
19-Jul-2005 08:39
One potentially useful feature is that in function and variable names bytes within 0x7f-0xff are allowed. This means you can use any UTF-8 in a variable name.

As a simple example (this only uses latin-1 characters, but the concept is the same):

<?php
function
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
банкир ру, квартиры в екатеринбурге в ипотеку - кредитный калькулятор автокредит ; Сантехника Мебель для ванной Акватон Минима 65 Z058440144362 Z348613067571