022PHP_ Variable variables - Manual.pdf

Embed Size (px)

Citation preview

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    1/30

    [edit] Last updated: Fri, 20 Apr 2012

    Variable variables

    Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable

    is set with a statement such as:

    A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a

    variable by using two dollar signs. i.e.

    At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this

    statement:

    produces the exact same output as:

    i.e. they both produce: hello world.

    In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if yo

    meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    1 of 30 26/04/2012 12:09

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    2/30

    1 of 30 26/04/2012 12:09

    is: ${$a[1]} for the first case and ${$a}[1] for the second.

    Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is

    made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name o

    the property of$foo. This is also true if $bar is an array access.

    Example #1 Variable property example

    The above example will output:

    I am bar.

    I am bar.

    Warning

    Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable

    $this is also a special variable that cannot be referenced dynamically.

    User Contributed Notes Variable variables

    ckelley at ca-cycleworks dot com 01-Apr-2012 03:34

    Unlike as stated near the bottom of this thread, using variables to point to an object does not always work. In my case, that is the object

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    2 of 30 26/04/2012 12:09

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    3/30

    returned from `new SimpleXMLElement($xmlstr)`.

    Once my nodes got 3 and 4 deep to access customer information from orders, I knew something drastic had to be done.

    Anonymous 08-Feb-2012 07:28

    Correction to [antony dot booth at nodomain dot here 19-Sep-2002 07:17]; in the extract() builtin array function, prefixes are

    automatically separated from the array key by an underscore character. Therefore --

    extract( $array, EXTR_PREFIX_ALL, "my_prefix_");

    Would create variables:

    $my_prefix__one (not $my_prefix_one)

    $my_prefix__two (not $my_prefix_two)

    $my_prefix__three (not $my_prefix_three)

    Omar Juvera 07-Aug-2011 09:13

    In this example, I have the variable $city.

    To store the variable $city inside another variable:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    4/30

    $var_container = 'city'; //$var_container will store the variable $city

    echo "CONTAINER's var: " . $var_container;

    echo "
    ";

    echo "CONTAINER's value: " . $$var_container;

    echo "
    ";

    echo "VAR city: " . $city;

    ?>

    The OUTPUT is:

    CONTAINER's var: city

    CONTAINER's value: New York

    VAR city: New York

    Omar Juvera 07-Aug-2011 01:40

    The example given in the php manual is confusing!

    I think this example it's easier to understand:

    The OUTPUT is:VARIABLE: new_variable_1

    VALUE: value 1

    You can also create new variables in a loop:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    5/30

    $var_name[] = "new_variable_" . $i; //$var_name[] will hold the new variable NAME

    }

    ${$var_name[0]} = "value 1"; //Value of $new_variable_1 = "value 1"

    ${$var_name[1]} = "value 2"; //Value of $new_variable_2 = "value 2"

    ${$var_name[2]} = "value 3"; //Value of $new_variable_3 = "value 3"

    ${$var_name[3]} = "value 4"; //Value of $new_variable_4 = "value 4"

    ${$var_name[4]} = "value 5"; //Value of $new_variable_5 = "value 5"

    echo "VARIABLE: " . $var_name[0] . "\n";

    echo "
    ";

    echo "VALUE: " . ${$var_name[0]};

    ?>

    The OUTPUT is:

    VARIABLE: new_variable_1

    VALUE: value 1

    andre at AWizardOfAss dot com 21-Jan-2011 01:39

    To generate a family of variables, such as $a1, $a2, $a3, etc., one can use "variable variables" as follows:

    Note that the correct syntax is ${a.$i} rather than the perhaps more intuitive $a{$i}

    The dot (.) is the string concatenation operator.

    A family of variables might be used as an alternative to arrays.

    Sam Yong - hellclanner at live dot com 21-Aug-2010 02:42

    Want to access object's property or array value using variable variables but not possible?

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    5 of 30 26/04/2012 12:09PHP V i bl i bl M l h // h / l/ /l i bl i bl h

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    6/30

    Here's a workaround to it:

    Cheers

    Sam-Mauris Yong

    mason 28-Jun-2010 12:39

    PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    6 of 30 26/04/2012 12:09PHP V i bl i bl M l htt // h t/ l/ /l i bl i bl h

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    7/30

    Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

    userb at exampleb dot org 08-Apr-2010 02:39

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    8/30

    $$$$$$a; //Returns Hello

    $$$$$$$a; //Returns World

    //... and so on ...//

    ?>

    dlorre at yahoo dot com 16-Feb-2010 12:04

    Adding an element directly to an array using variables:

    will issue this error:

    Fatal error: Cannot use [] for reading

    This is not a bug, you need to use the {} syntax to remove the ambiguity.

    php at willshouse dot the-usual-uk-tld 21-Nov-2009 04:14

    If you need to access one of the superglobals using a variable variable, you can look it up in $GLOBALS:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    9/30

    i f ( ! array_key_exists( $fieldName, $getpost ) ) { return $defaultValue; }

    if ( empty( $getpost[ $fieldName ] ) ) { return $defaultValue; }

    return $getpost[ $fieldName ];

    }

    echo "\n";

    ?>

    al at o3strategies dot com 15-Nov-2009 06:01

    This is an extremely handy use for variable variables especially when dealing with direct data modeling. This will allow you to

    automatically set object properties based on a query result. When new fields are added to the table, the class will receive these

    properties automatically. This is great for maintaining user data or other large tables. Your property names will be bound to your column

    name in the database, making maintenance worry free. This method uses $this->{$var} for the variable variable creation.

    Matthew (mwwaygoo AT hotmail DOT com) 02-Nov-2009 08:03

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    9 of 30 26/04/2012 12:09 PHP: Variable variables Manual http://www php net/manual/en/language variables variable php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    10/30

    A note on Variable variables/functions and classes

    To store a function name in a variable and call it later, within a class, you do the following:-

    This allows you to specify the function required. It works better then a big switch statement as it allows for extending the class moreeasily. (ie adding display_ES(); )

    moomin 24-Jun-2009 08:58

    If $something is 'myvar' then you can use $obj->{"_$something"} to get the value of $obj->_myvar without having to use eval.

    aditeojr at yahoo dot co dot uk 01-Jun-2009 02:36

    Parsing and retrieving a value from superglobals, by a specified order, looping until it find one :

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    10 of 30 26/04/2012 12:09 PHP: Variable variables - Manual http://www php net/manual/en/language variables variable php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    11/30

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

    11 of 30 26/04/2012 12:09 PHP: Variable variables - Manual http://www php net/manual/en/language variables variable php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    12/30

    php at ianco dot co dot uk 28-May-2009 02:47

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    13/30

    $var = VariableArray($bar, $baz); //$var now contains int(8)

    ?>

    You can simply pass in a superglobal as the first argument. Note for associative arrays don't put quotes inside the square braces unless

    you adjust the regexp to accept it. I wanted to keep it simple.

    Anonymous 30-Nov-2008 07:44

    I have a HTML form that has a dynamic number of fields (for entry of collected data it adds a new field each time) and would like to use

    the variable variable on _POST. This way, I could increment the field name value with a loop limit when say 100 fields are reached (themax for the form.)

    Below is the solution I came up with to work around it:

    nullhility at gmail dot com 06-Jun-2008 12:43

    It's also valuable to note the following:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    14/30

    ${date("M")} = "Worked";

    echo ${date("M")};

    ?>

    This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same

    variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo

    statement. Have fun ;).

    Nathan Hammond 11-Feb-2008 03:41

    These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent

    upon the current scope.

    j3nda at fv dot cz 30-Dec-2007 01:23

    PHP: Variable variables Manual http://www.php.net/manual/en/language.variables.variable.php

    14 f 30 26/04/2012 12 09 PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    15/30

    hi, i handling multi-array with like this:

    i use this for some classes with direct access to $__info array. and i have some config_{set|get} static functions without this class, but

    handling is the same.

    i'm not testing this piece of code for benchmark and high load.

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    16/30

    return false;

    }

    // debug || vyjimka

    ');

    return false;

    }

    ?>

    craigmorey at gmail dot com 27-Dec-2007 08:23

    For a long time I've been trying to use variable variables to figure out how to store and retrieve multi-dimensional arrays in a MySQL

    dbase. For instance, a config setting stored in a complex array might resemble the below:

    The most obvious way for storing this info in a dbase (discounting XML/JSON) is to store a "path" (of the nesting) and a "value" in a

    database record:

    'modules,module_events,settings,template,name' = 'List Page'

    But storing it is only part of the problem. PHP variable variables are no use to try and interpret string representations of arrays, eg it

    will see the string representation of a nested array such as config['modules']['module_events'] as a single variable called

    'config[modules][module_events]', so loops that parse the "path" into a variable variable don't help.

    So here is a little function that parses an array of "paths" and "value" strings (eg from a dbase) into a multi-dimensional nested array.

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    17/30

    continue;

    }

    # reverse sort the keys so we'll start building from

    # the bottom, not the top

    krsort($temp1);

    # start with the temporary array off with the end value

    $temp2 = $val1;

    # loop through the nested keys

    foreach($temp1 AS $val2) {

    # if this nested key has no name,

    # (and isn't "0") skip this cycle

    if ($val2===false) {

    continue;

    }

    # gradually build up the this temporary nested array

    # from the leaf, working up the branches to the trunk

    $temp2 = array($val2 => $temp2);

    }

    # for this cycle, dump this bucketful of data into the bathtub

    $output_array = array_merge_recursive($output_array,$temp2);

    }return $output_array;

    }

    ?>

    correojulian33-php at yahoo dot es 28-Nov-2007 06:59

    This example may help to overcome the limitation on $this.

    Populate automatically fields of an object form a $_GET variable.

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    18/30

    } // while

    var_dump($this);

    }

    }

    $_GET['prop1']="uno";

    $_GET['prop2']="dos";

    $_GET['prop3']=array('tres','cuatro','cinco','seis');

    $p=new pp();

    $p->fun1();

    ?>

    output is ...

    object(pp)#1 (3) {

    ["prop1"]=>

    &string(3) "uno"

    ["prop2"]=>

    &string(3) "dos"

    ["prop3"]=>&array(4) {

    [0]=>

    string(4) "tres"

    [1]=>

    string(6) "cuatro"

    [2]=>

    string(5) "cinco"

    [3]=>

    string(4) "seis"

    }

    }

    the_tevildo at yahoo dot com 13-Oct-2007 06:22

    This is a handy function I put together to allow variable variables to be used with arrays.

    To use the function, when you want to reference an array, send it in the form 'array:key' rather than 'array[key]'.

    For example:

    p p p g g p p

    18 f 30 26/04/2012 12 09 PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    19/30

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    20/30

    echo '
    ';

    var_dump($temp_var);

    echo '
    ';

    ?>

    Sinured 11-Jun-2007 06:07

    One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also

    possible.

    This syntax doesn't work for functions:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    21/30

    fabio at noc dot soton dot ac dot uk 11-Oct-2005 04:15

    A static variable variable sounds like an oxymoron and indeed cannot exist. If you define:

    you get a parse error.

    Regards,

    Fabio

    rafael at fuchs inf br 21-Mar-2005 08:08

    You can use constants in variable variables, like I show below. This works fine:

    output:

    Fuchs

    21 of 30 26/04/2012 12:09

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    22/30

    Test

    Anonymous 13-Mar-2005 07:25

    It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:

    This is apparent from the notes others have left, but is not explicitly stated.

    Shawn Beltz 02-Mar-2005 12:06

    Multidimensional variable variables. If you want to run the below as one big program, you'll have to undefine $foo in between assignments.

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    23/30

    $erf = eval("return \$$ref;");

    print $erf;

    # prints "this is foo."

    $foo[1]['a_z'] = "this is foo[1][a_z].";

    $ref = "foo[1][a_z]";

    $erf = eval("return \$$ref;");

    print $erf;

    # prints "this is foo[1][a_z]."

    ?>

    sir_hmba AT yahoo DOT com 06-May-2003 03:08

    This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.

    Here's the code:

    23 of 30 26/04/2012 12:09

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    24/30

    And here's the output:

    f->bar=3 f->baz=6

    $obj=f $attr=bar $val=3

    antony dot booth at nodomain dot here 19-Sep-2002 07:17

    You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -

    This however would be reinventing the wheel when you can simply use:

    Note that this will overwrite the contents of variables that already exist.

    Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -

    EXTR_PREFIX_ALL

    This would create variables: -

    $my_prefix_one

    24 of 30 26/04/2012 12:09

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    25/30

    $my_prefix_two

    $my_prefix_three

    containing: -

    "First Value", "2nd Value" and "8" respectively

    jupp-mueller at t-online dot de 08-Sep-2002 06:29

    I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:

    thien_tmpNOSPAM at hotmail dot com 20-Aug-2002 03:37

    You can also use variable variables and the string concat operator to generate suffixed (or prefixed) variables based on a base name.

    For instance, if you wanted to dynamically generate this series of variables:

    base1_suffix1

    base1_suffix2

    base2_suffix1

    base2_suffix2

    base3_suffix1

    base3_suffix2

    You can do this:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    26/30

    $bases = array('base1', 'base2', 'base3');

    $suffixes = array('suffix1', suffix2);

    foreach($bases as $base) {

    foreach($suffixes as $suffix) {

    ${$base.$suffix} = "whatever";

    #...etc

    }

    }

    ?>

    J. Dyer 12-Aug-2002 01:05

    Another use for this feature in PHP is dynamic parsing..

    Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation

    in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are

    required for the current one.

    Normally, you won't need something this convolute. In this example, I needed to load an array with dynamically named objects - (yes, this

    has some basic Object Oriented programming, please bare with me..)

    Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant

    on the previous ones.

    26 of 30 26/04/2012 12:09

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    27/30

    I haven't fully tested the implimentation of the objects. The scope of a variable-variable's object attributes (get all that?) is a

    little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious,

    extra hard-coding is the only alternative.

    Then, we can easily pull everything back out again using a basic array function: foreach.

    Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.

    27 of 30 26/04/2012 12:09

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    28/30

    04-Jun-2002 11:34

    The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces. Observe:

    This works for L-values as well. So the below works the same way:

    NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2

    chrisNOSPAM at kampmeier dot net 08-Aug-2001 10:40

    Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve

    the ambiguity. For example:

    mstearne at entermix dot com 10-May-2001 06:09

    Variable variables techniques do not work when one of the "variables" is a constant. The example below illustrates this. This is probably

    28 of 30 26/04/2012 12:09

    PHP: Variable variables - Manual http://www.php.net/manual/en/language.variables.variable.php

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    29/30

    the desired behavior for constants, but was confusing for me when I was trying to figure it out. The alternative I used was to add the

    variables I needed to the $GLOBALS array instead of defining them as constants.

    [Editor Note: For variable constants, use constant() --Philip]

    bpotier at edreamers dot org 26-Feb-2001 09:11

    A good example of the use of variable variables name. Imagine that you want to modify at the same time a list of more than one record from

    a db table.

    1) You can easily create a dynamic form using PHP. Name your form elements using a static name and the record id

    ex:

  • 7/28/2019 022PHP_ Variable variables - Manual.pdf

    30/30

    By the way...

    Variable variables can be used as pointers to objects' properties:

    outputs: another variable: b

    mccoyj at mail dot utexas dot edu 03-Nov-2000 03:36

    There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the

    reference is variable...usually with arrays.

    This code outputs "foo" using PHP 4.0.3.

    Hope this helps...

    - Jordan

    Copyright 2001-2012 The PHP GroupAll rights reserved.