PHP 5.6.0beta1 released
add a note add a note

User Contributed Notes 20 notes

up
2
info at warpdesign dot fr
5 years ago
Note about function names:
--

According to the specified regular expression ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*), a function name like this one is valid:

<?php
function ()
{
   echo
'foo';
}
?>

And PHP interpreter correctly interprets the function. However some parsers (ex: PDT/Eclipse) does not see this as a valid function name, and only accept function names starting with a letter or an underscore.
up
1
spy-j at rainbowtroopers dot com
9 years ago
Take care when using parameters passed by reference to return new values in it:

<?PHP

function foo( &$refArray, ....) {
 
  UNSET(
$refArray); //<-- fatal!!!

 
for (....) {
   
$refArray[] = ....
  }
//end for

}//end foo

?>

I tried to make sure the passed variable is empty so i can fill it up as an array. So i put the UNSET. Unfortunately, this seems to cause a loss with the reference to the passed variable: the filled array was NOT returned in the passed argument refArray!

I have found that replacing unset as follows seems to work correctly:

<?PHP

function bar( &$refArray, ....) {
   
  if (!EMPTY(
$refArray)) $refArray = '';

  : : :

}
//end bar

?>
up
-2
tom pittlik
8 years ago
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:

<?php

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"

?>
up
-2
gnirts dot REMOVE_THIS at HATE_SPAM dot gmail dot com
8 years ago
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;
    }
}

?>
up
-4
p at onion dot whitefyre dot com
8 years ago
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 ($n) {
    return
pow($n, 2);
}

function
($string) {
    return
'<p>'.str_replace("\n\n", "</p>\n<p>", $string).'</p>';
}

echo
(4); //16

echo ("Some text\n\nbroken into paragraphs");
?>

You can use this to write PHP code in your native language, or even better make creative use of symbols like above to make your code understandable by everyone.
up
-4
GMCardoe at netherworldrpg dot net
13 years ago
Stack overflow means your function called itself recursivly too many times and just completely filled up the processes stack. That error is there to stop a recursive call from completely taking up the entire system memory.
up
-4
php at paintbot dot com
14 years ago
Important Note to All New Users: functions do NOT have default access to GLOBAL variables.  You must specify globals as such in your function using the 'global' type/keyword.  See the section on variables:scope.

This note should also be added to the documentation, as it would help the majority of programmers who use languages where globals are, well, global (that is, available from anywhere).  The scoping rules should also not be buried in subsection 4 of the variables section.  It should be front and center because I think this is probably one of the most non-standard and thus confusing design choices of PHP.

[Ed. note: the variables $_GET, $_POST, $_REQUEST, $_SESSION, and $_FILES are superglobals, which means you don't need the global keyword to use them inside a function]
up
-5
leblanc at tamu dot edu
7 years ago
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
up
-5
fabio at city dot ac dot uk
12 years ago
As a corollary to other people's contributions in this section, you have to be careful when transforming a piece of code in to a function (say F1). If this piece of code contains calls to another function (say F2), then each variable used in F2 and defined in F1 must be declared as GLOBAL both in F1 and F2. This is tricky.
up
-7
aboyd at ssti dot com
13 years ago
[Editor's note: put your includes in the beginning of your script. You can call an included function, after it has been included                --jeroen]

The documentation states: "In PHP 3, functions must be defined before they are referenced. No such requirement exists in PHP 4."

I thought it wise to note here that there is in fact a limitation: you cannot bury your function in an include() or require().  If the function is in an include()'d file, there is NO way to call that function beforehand.  The workaround is to put the function directly in the file that calls the function.
up
-8
dma05 at web dot de
8 years ago
@ gilthansNOSPAAM at gmailSPAAMBLOCK dot com

i think you just fried your stack like the manual reads ;)
works up to ~17000-30000 iterations for me... although, that's on a linux box with php5 as an apache2 module...
maybe the cgi version has a smaller stack...

the problem seems logical, because every time your function iterates, it puts another pointer on the stack (the one to your variable), and sooner or later you're out of memory there, so no more pointers to be added which should make it crash, if you're using one global variable, then there's no pointers to be added to your stack and it won't run out (well, not so fast at least, you still need to add other pointers to the stack but at least one less)...
up
-11
xpaz at somm dot com
12 years ago
It is possible to define a function from inside another function.
The result is that the inner function does not exist until the outer function gets executed.

For example, the following code:

<?php

function a () {
  function
b() {
    echo
"I am b.\n";
  }
  echo
"I am a.\n";
}
if (
function_exists("b")) echo "b is defined.\n"; else echo "b is not defined.\n";
a();
if (
function_exists("b")) echo "b is defined.\n"; else echo "b is not defined.\n";

?>

echoes:

b is not defined.
I am a.
b is defined.

Classes too can be defined inside functions, and will not exist until the outer function gets executed.
up
-12
Gautam
6 years ago
<?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 !!!
*/
?>
up
-9
gilthansNOSPAAM at gmailSPAAMBLOCK dot com
9 years ago
Note that a function that calls a variable by reference CANNOT be used recursively, it will generate a CGI error (at least on my windows platform).
Thus:
<?php
$foo
= 0;
function
bar(&$foo){
   
$foo++;
    echo
$foo."\n";
    if(
$foo < 10)
       
bar($foo);
}
?>
Will NOT work.
Instead, you should just use global variables.
<?php
$foo
= 0;
function
bar(){
    global
$foo;
   
$foo++;
    echo
$foo."\n";
    if(
$foo < 10)
       
bar($foo);
}
?>
This, of course, assuming that you need to use $foo in other functions or parts of code. Otherwise you can simply pass the variable regulary and there should be no problems.
up
-9
kop at meme dot com
13 years ago
See also about controlling the generation of error messages by putting @ in front of the function before you call it, in the section "error control operators".
up
-11
cap at capsi dot cx
14 years ago
When using a function within a function, using global in the inner function will not make variables available that have been first initialized within the outer function.
up
-10
php at simoneast dot net
11 years ago
If you're frustrated by not having access to global variables from within your functions, instead of declaring each one (particularly if you don't know them all) there are a couple of workarounds...

If your function just needs to read global variables...

function aCoolFunction () {
    extract($GLOBALS);
....

This creates a copy of all the global variables in the function scope.  Notice that because it's a copy of the variables, changing them won't affect the variables outside the function and the copies are lost at the conclusion of the function.

If you need to write to your global variables, I haven't tested it, but you could probably loop through the $GLOBALS array and make a "global" declaration for each one.  Then you could modify the variables.

Please note that this shouldn't be standard practice, but only in the case where a function needs access to all the global variables when they may be different from one call to another.  Use the "global var1, var2..." declaration where possible.

Hope that helps some people.

Simon.
up
-13
email at fake dot com
6 years ago
You can set variable DEFAULT values for a function in the (). These will be over-written by any input values (or non values).

<?php

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

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

?>

OUTPUT:
----------

a = 123
b = 456

a = overwritten
b = 987654321

a =
b = var A has to be overwritten.
up
-14
roy at intelligentdashimaging dot com
9 years ago
Here's how to get static function behavior and instantiated object behavior in the same function
<?php

// Test of static/non-static method overloading, sort of, for php
class test {
    var
$Id = 2;
    function
priint ($id = 0) {
        if (
$id == 0) {
            echo
$this->Id;
            return;
        }
        echo
$id;
        return;
    }
}
$tc = new test ();
$tc->priint ();
echo
"\n";
test::priint (1);
/* output:
2
1
*/
?>
up
-14
bishop
11 years ago
Consider:

<?php

function a() {
    function
b() {
        echo
'I am b';
    }
    echo
'I am a';
}

a();
a();

?>

As you might NOT expect, the second call to a() fails with a "Cannot redeclare b()" error.  This behaviour is correct, insofar as PHP doesn't "allow functions to be redefined."

A work around:

<?php

function a() {
    if ( !
function_exists('b') ) {
        function
b() {
            echo
'I am b';
        }
    }
    echo
'I am a';
}
?>
To Top