2

I have two config files. The first, which is called configs.php contains an array with some values:

$welcomeConfigs = [
  "title" => "welcome",
  "description" => "a description"
];

The second file includes the configs.php one and use the its array to generate some other variables. The second file is called views.php.

$viewConfigs = VIEW . 'Configs';
$pathToViewConfigs = VIEW . '/configs.php';

include($pathToViewConfigs);

var_dump($$viewConfigs);

In index.php:

define("VIEW", "welcome");
include('views.php');

I need to store in the $title variable, for example, the value of the associative array, but when I try to do it nothing happens. I tried to use var_dump to check if the syntax was correct and I used en external fiddle to check if something was wrong, but nothing is actually wrong.

When type var_dump($$viewConfigs); the output is { ["title"]=> string(7) "welcome" ["description"]=> string(13) "a description" }

but when I type var_dump($$viewConfigs['title']); the output is NULL.

How can I fix this? What I am doing wrong?

ctrlmaniac
  • 404
  • 4
  • 13
  • 28

1 Answers1

2

You have to use this syntax:

var_dump( ${$viewConfigs}['title'] );

that interpret $viewConfigs as variable name. The form $$viewConfigs['title'] interpret as variable name the content od $viewConfigs['title'], that not exists.

I hope I have been clear.

(Edit:) See more about variable variables on PHP Official site

fusion3k
  • 11,568
  • 4
  • 25
  • 47
  • Thank you that is correct!! (I have to wait 6 minutes before checking it as the correct answer though) – ctrlmaniac Feb 03 '16 at 00:05
  • 2
    Yes, and from the manual on "variable variables" the pertinent section: "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 you 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 is: ${$a[1]} for the first case and ${$a}[1] for the second." – gview Feb 03 '16 at 00:07
  • @gview Thank you. I have added the link in the answer. – fusion3k Feb 03 '16 at 00:09