Variable variables seem pretty cool, but I can't think of a scenario where one would actually use them in a production environment. What would such a scenario be? How were they used?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
A variable variable is essentially an array (map/dictionary). The following are equivalent ideas:
Thus if you wrap your "variable variables" into a parent array, you can do away with them.
I've seen people use variable properties inside classes:
But again, you could use an array:
And outside classes:
So you never "have" to use variable variables or variable properties when writing your own controlled code. My personal preference is to never use variable variables. I occasionally use variable properties, but prefer to use arrays when I'll be accessing data in that way.
Think of it for use in a template system where you are using PHP files and need to set in variables:
Now assuming you used these variable names in your template, you could call it and pass variables into it for use.
Then in your template:
I found it useful in a single scenario. I was having YouTube API results in JSON format, like this
So I used it like
So it worked for me here :)
I mainly use it to reduce copy-paste in sanitizing get/post data in the begining of a php file: It makes sanitized variables with the proper names:
instead of all these lines:
I hope it helps
Personally, I use them fairly often. All calls of the following types use variable-variables:
So any time you do a dynamic method/function call, you're using variable-variables...
A common use for this is accessing protected properties via the
__get
magic method. I've seen the following quite often:Which by definition is using variable variables to provide read-access to the protected members...
I've never directly used the
$$var
syntax (and don't think I ever will). I have seen it used to access global variables by nameglobal $$name; echo $$name;
, but the same thing can be done with the$_GLOBALS[$name]
syntax, so that's not a good use-case (not to mention that using global variables is usually seen as bad practice)...Its purpose, I guess, is to allow novice programmers to dynamically change data without using "complicated stuff" like composite types (arrays and objects).
I never use them.