|
|
Глава 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;
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
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";
}
}
foo();
bar();
?>
|
|
PHP не поддерживает перегрузку функции, также отсутствует возможность
переопределить или удалить объявленную ранее функцию.
Замечание:
Имена функций регистронезависимы, тем не менее, более предпочтительно
вызывать функции так, как они были объявлены.
PHP 3 не поддерживает переменное количество аргументов функции,
хотя поддержка значений по умолчанию для аргументов присутствует (смотрите раздел
Значения аргументов по умолчанию).
Начиная с 4-й версии PHP поддерживает и то, и другое: смотрите раздел
Списки аргументов переменной длины
и описания функций
func_num_args(),
func_get_arg(), и
func_get_args() для более детальной информации.
SID TRIVEDI
25-Oct-2007 11:56
<?php
$a = null;$b =null; function arithmatic($a,$b){
global $sum; global $array; $sum = $a + $b;
$dif = $a - $b;
$mul = $a * $b;
$div = bcdiv($a,$b,2);$array = array($a, $b, $sum, $dif, $mul, $div);
return $array;
}
arithmatic(11,5); 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>";
?>
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
$text= 'This Line is Bold and Italics.';
function makebold_n_italics($text)
{
$text = "<i><b>$text</i></b>";
return($text); }
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"; $thanks='Thanks to Zeev Suraski and Andi Gutmans !!!';
$text=$thanks;
echo makebold_n_italics("$text");
?>
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
function plus($a, $b){
$c=$a+$b;
echo "$a+$b=$b </br>";
}
plus(2,3);
$vars ='plus';
$vars(2,3); ?>
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($some_vars1, $some_vars2, $some_vars3, $some_vars4); ?>
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); implode(",",$arr,$set_var); implode(",",$arr,$unset_var); implode(",",$arr,NULL); myimplode(",",$arr,$set_var); ?>
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
|
|