Variable Variables in PHP
PHP, WordPress
PHP allows you to set dynamic variable names. This can be very useful when working with arrays and loops.
To use a variable in a variable declaration, wrap the declaration in curly brackets.
This is an example of a variable variable being used to build a form element in the context of a WordPress widget:
<?php
$options = ['mobile', 'landline']
foreach ($options as $option) {
$fieldname = $option . '_text';
?>
<label>
Set the text for <?= $option; ?>
<input
type="text"
name="<?= $this->get_field_name( $fieldname ); ?>"
value="<?= ${$option . '_text'}; ?>" />
</label><br>
<?php
}
?>
In this example, during each loop the “value” attribute is set to a variable which is built on the fly. During the first iteration, the value attribute looks like value="<?= $mobile_text; ?>"
. This variable allows us to retrieve previously saved data that is represented by $mobile_text
. On the next loop, the value will be set to $landline_text
.
Resources
comments powered by Disqus