Dynamic access to a PHP array

后端 未结 4 400
逝去的感伤
逝去的感伤 2021-01-13 05:27

I tried to access with $this->$arrDataName[$key] on the element with the key $key from the array $this->$arrDataName. But PHP in

相关标签:
4条回答
  • 2021-01-13 06:08

    Let's assume your array is $this->arrDataName. You have a $key, so your object would be $this->arrDataName[$key].

    If you want the contents of the variable which name is stored in $this->arrDataName[$key] you should do this:

    <?php
        echo ${$this->arrDataName[$key]};
    ?>
    
    0 讨论(0)
  • Your syntax is correct:

    $this->{$varName}[$key]
    

    You can also use an extra variable for this:

    $myTempArr = $this->$arrDataName;
    
    $myTempArr[ $key ];
    

    IMHO, readability is better that way...

    0 讨论(0)
  • 2021-01-13 06:17

    Well, as far as I know, it works. Here how I tested it:

    <?php
    class tis
    {
        var $a = array('a', 'b', 'c');
        var $b = array('x', 'y', 'z');
    
        public function read($var)
        {
            echo $this->{$var}[1].'<br />';
        }
    }
    
    $t = new tis();
    $t->read('a');
    $t->read('b');
    ?>
    

    And the output:

    b
    y
    

    Check correctness of $arrDataName. Turn on debuging and displaying PHP erros (including notices). Maybe you're trying to read non-existing property?

    Also, which PHP version you use? I assume PHP5?

    0 讨论(0)
  • 2021-01-13 06:29
    <?php
        class Foo {
            public function __construct() {
                $this->myArray = array('FooBar');
                $arrayName = 'myArray';
                echo $this->{$arrayName}[0];
            }
        }
        new Foo;
    

    This worked perfectly for me, it printed FooBar.

    0 讨论(0)
提交回复
热议问题