php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #53750 dynamic variable name problem
Submitted: 2011-01-14 17:58 UTC Modified: 2011-01-17 05:12 UTC
From: tuhin dot barua at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.17 OS: ubuntu
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: tuhin dot barua at gmail dot com
New email:
PHP Version: OS:

 

 [2011-01-14 17:58 UTC] tuhin dot barua at gmail dot com
Description:
------------
example 1:

php > $a = new stdclass();
php > $a->arr = array(1,2,3);
php > $arr = 'arr';
php > print_r($a->$arr);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
php > print_r($a->$arr[0]);
php >

example 2:

php > $arr = array(1,2,3);
php > $a = 'arr';
php > print_r($$a);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
php > print_r($$a[0]);
arr
php > print_r($$a[1]);
php >

Test script:
---------------
$a = new stdclass();
$a->arr = array(1,2,3);
$arr = 'arr';
print_r($a->$arr);
print_r($a->$arr[0])



Expected result:
----------------
cant access array elements with a dynamic variable name.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-01-17 05:12 UTC] aharvey@php.net
-Status: Open +Status: Bogus -Package: Arrays related +Package: Scripting Engine problem
 [2011-01-17 05:12 UTC] aharvey@php.net
This is a simple operator associativity issue: $a->$arr[0] is actually parsed as $a->{$arr[0]}, and since the first character of $arr is "a", the last line in the test script ends up effectively being print_r($a->a).

You can work around this by changing the last line of the script to:
print_r($a->{$arr}[0]);
 [2011-01-26 23:35 UTC] tuhin dot barua at gmail dot com
ok.
but how about this one ?

lets say this is the object

FacebookApiException Object
(
    [result:private] => Array
        (
            [error] => Array
                (
                    [type] => OAuthException
                    [message] => Invalid OAuth access token.
                )

        )

    [message:protected] => Invalid OAuth access token.
)

how do i access field something like 'message:protected' ?

$field = 'message:protected';
$object->$field  // dont work in this case neither does $object->{$field}
is that a bug?

this kinda problem i faced with google data api as well... google has some field name like dc:date ... and i had to change it to dc_date before i can access it.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Fri Feb 06 17:00:02 2026 UTC