首页 > 解决方案 > 括号中的变量是什么意思?

问题描述

今天发现了一段奇怪的php代码:

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>';
    }

这是什么意思?

我相信标有 $option['type'] 的括号是解释器应该使用的变量。没有它们,我得到一个错误:“数组到字符串的转换”。

我对吗?

标签: php

解决方案


这就是您请求数组键值的方式。所以 $option 是一个带键的数组。这些键之一是“类型”。

要获取数组$option 的值,您可以像这样在括号之间添加键

$options['type']

如果 $options 是一个对象,您可以获得如下值:

$options->type

使用大括号是因为在脚本中您使用 $options['type'] 的值来调用当前对象中的函数。

如果 $options['type'] 的值为example,则以下代码相等

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

等于

$this->example($options);

推荐阅读