Alexander Behling
Alexander Behling

Reputation: 617

What does a variable enclosed in brackets mean?

Today I found some strange piece of php code:

function wt_render() {
        echo '<div class="wrap theme-options-page clearfix"';
        global $wp_version;
        if(version_compare($wp_version, "3.5", '>')){
            echo ' data-version="gt3_5"';
        }
        echo '>';
        echo '<form method="post" action="">';

        foreach($this->options as $option) {
            if (method_exists($this, $option['type'])) {
                $this->{$option['type']}($option);
            }

        }
        echo '</form>';
        echo '</div>';
    }

What does this mean?

I believe the bracket marked $option['type'] as a variable the interpreter should use. Without them, I got an error: "Array to String conversion".

Am I right?

Upvotes: 0

Views: 563

Answers (2)

Remco K.
Remco K.

Reputation: 717

That's how you request the value of an array key. So $option is an array with keys. One of these keys is 'type'.

To get the value of the array $option you can add the key between the brackets like this

$options['type']

If $options was an object you could get the value like this:

$options->type

The use of the curly brackets is because in the script you use the value of $options['type'] to call a function in the current object.

If the value of $options['type'] is example the codes below are equal

$this->{$options['type']}($options);

Equals

$this->example($options);

Upvotes: 2

Chocolord
Chocolord

Reputation: 493

This syntax can be used to use a pointers of methods

example

$dateTime = new DateTime();
$dateTime->{"add"}(new DateInterval("P3D"));

$methods = array("getTimezone", "getTimestamp", "getOffset");
foreach($methods as $method) var_dump($dateTime->{$method}());

Upvotes: 0

Related Questions