1

I want to import data from a .json file into a PHP file and dynamically, by using variable variables and a foreach loop, define new variables. However, PhpStorm doesn't recognize my variables and give me Undefined variable warnings. What to do?

Consider a file data.json with some data, and it exists and is readable. The main code is something like this:

foreach (json_decode(file_get_contents("data.json"), true) as $varName => $value)
    $$varName = $value;

Note: I don't want neither to use PHPDoc, nor to disable "undefined variable" inspection (thanks LazyOne).

UPDATE: Thanks to LazyOne's comment, I'll use PHP files instead of JSON ones to save data.

13
  • 1
    Is there any reason you don't want to keep it as an array, it's much more flexible and less prone to problems. Commented Jun 17, 2018 at 17:51
  • 1
    "I don't want to use PHPDoc" Well ... then only other option is to disable that "unknown variable" inspection. Commented Jun 17, 2018 at 18:14
  • 2
    Your IDE won't know anything about variable variables. It would have to understand your JSON and how you interpret it, which is beyond the scope of what it can deal with. Commented Jun 17, 2018 at 18:25
  • 1
    You have no other choice: IDE has no idea where those variables come from and why they should be "ignored" by that inspection. You want to use "magic" -- be ready to face the consequence -- static analysis that IDE does right now does not allow to analyze such dynamic code. Commented Jun 17, 2018 at 18:38
  • 2
    I have no idea on what data you have got there and how else it is used / where it comes from etc. From speed point of view -- keep it as PHP array / constants / variables. If data comes from some external source / another language or service -- better use what you are using (JSON/YAML/XML). But you will have to waste some time for data parsing/conversion into PHP accessible form each time. Caching will help though. Commented Jun 17, 2018 at 18:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.