不要评估$ config变量

时间:2015-01-04 17:06:49

标签: php

我正在尝试编写配置文件。它将包含一个选项数组,数组名称将是 $config。在执行代码时,我收到Undefined variable: config

的错误消息

我希望$ cofig应该按原样写入文件而不是评估它。

$config_text = <<<FILECONTENT
<?php


$config = array(
    'Settings' => array(
        'SHOP_TITLE' => $this->request->data['Shop']['shop_name'] . ' - ' . $this->request->data['Shop']['admin_password'],
        'SHOP_ID' => $shop_id,
        'ANALYTICS' => '',
        'PAYPAL_API_USERNAME' => '',
        'PAYPAL_API_PASSWORD' => '',
        'PAYPAL_API_SIGNATURE' => '',
        'AUTHORIZENET_ENABLED' => '1',
        'AUTHORIZENET_API_URL' => 'https://test.authorize.net/gateway/transact.dll',
        'AUTHORIZENET_API_LOGIN' => '',
        'AUTHORIZENET_API_TRANSACTION_KEY' => '',
    )    
);
;
FILECONTENT;

1 个答案:

答案 0 :(得分:1)

var_export()的聪明方式:

要强制首先计算内部表达式,但仍然以PHP代码可解析格式生成输出,实际上是临时定义数组,以便将 计算为变量,然后调用{{3} }在该变量上,与$config =赋值一起将其放入字符串中。

// Actually create and evaluate a real array:
$defined_config = array(
    'Settings' => array(
        'SHOP_TITLE' => $this->request->data['Shop']['shop_name'] . ' - ' . $this->request->data['Shop']['admin_password'],
        'SHOP_ID' => $shop_id,
        'ANALYTICS' => '',
        'PAYPAL_API_USERNAME' => '',
        'PAYPAL_API_PASSWORD' => '',
        'PAYPAL_API_SIGNATURE' => '',
        'AUTHORIZENET_ENABLED' => '1',
        'AUTHORIZENET_API_URL' => 'https://test.authorize.net/gateway/transact.dll',
        'AUTHORIZENET_API_LOGIN' => '',
        'AUTHORIZENET_API_TRANSACTION_KEY' => '',
    )    
);

// Export it to a parseable format, passing `true` as the second arg
// so it returns the string
$defined_config_text = var_export($defined_config, true);

// Then create the text variable as a HEREDOC or double-quoted string. You will have to escape the opening `$`.
// This does it with a HEREDOC, so the variable is internally parsed.
$config_text = <<<FILECONTENT
<?php
\$config = {$defined_config_text}
;
FILECONTENT;

如果不需要,您可以丢弃$defined_config数组:

unset($defined_config);

虽然这在我自己的PHP解释器中有效,但由于输出中的<?php,我很难让在线解释器正常工作以用于演示目的。以下是部分有效的示例:var_export(),其中省略了<?php

丑陋的蛮力字符串连接方式:

你的另一个选择,设置起来比较简单但看起来更加丑陋只是将表达式连接成单引号字符串以生成有效的PHP代码。

// Create a big ugly string into which the expressions like 
// $this->request->data and $shop_id are concatenated
$config_text = '
<?php
$config = array(
     "Settings" => array(
            "SHOP_TITLE" => ' . $this->request->data['Shop']['shop_name'] . ' - ' . $this->request->data['Shop']['admin_password'] . ',
            "SHOP_ID" => ' . $shop_id . ',
            "ANALYTICS" => "",
            //etc....
      )
);
';
// ^^ Do not forget to close the single-quoted string and terminate ;
// Now your output string is complete in $config_text.