尝试将变量添加到此数组

时间:2018-03-15 22:53:41

标签: php

在谈到这一点时我不是很了解,但我正在学习。我已经尝试了一些我能想到的添加变量,所以我没有编辑这个文件。我希望将API密钥放在一个单独的配置文件中,以保持整洁,更容易进行更改,而不必记住必须为这些api密钥编辑的所有文件。这是我无法弄清楚的代码。

private $_nodes = array("https://omdbapi.com/?apikey=123456&i=%s");

我试过这个,但没有快乐。无法弄明白。我尝试了很多变化。也许这在阵列中甚至不可能,就像我说的,我有很多东西需要学习

private $_nodes = array("https://omdbapi.com/?apikey='"$site_config['OMDBAPIKEY']"'&i=%s");

我已经设法将所有其他API密钥移动到配置中,但是这个不能正常工作

3 个答案:

答案 0 :(得分:2)

我想我看到了两个问题。

一个肯定是语法错误。您需要使用.运算符将字符串连接在一起。

private $_nodes = array("https://omdbapi.com/?apikey='" . $site_config['OMDBAPIKEY'] . "'&i=%s");

private暗示这是初始化对象属性。使用您的数组值将导致

  

致命错误:常量表达式包含无效操作

如果要使用该值指定它,可以在构造函数中执行此操作。

private $_nodes;

function __construct()
{
    $this->_nodes = array("https://omdbapi.com/?apikey='". $site_config['OMDBAPIKEY'] . "'&i=%s");
}

$site_config在此示例中未定义,但我不知道它来自何处。您必须以某种方式在构造函数的范围内定义它。也许将其传递为一个参数。)

答案 1 :(得分:0)

正如Don't Panic's answer所说,你遇到的第一个问题是必须使用串联.运算符将字符串连接(连接)在一起。

正如答案所说,你也无法在类定义中使用变量的值定义对象属性。

可以使用常量值。因此,首先需要将$site_config更改为const而不是变量:

const Site_Config = array(
    'OMDBAPIKEY' => 123456,
    /* other definitions */
);

class SomeUsefulClass {
    private $_nodes = array("https://omdbapi.com/?apikey='" . Site_Config['OMDBAPIKEY'] . "'&i=%s")
}

这是否是一个好主意肯定是值得怀疑的......

答案 2 :(得分:0)

代码的问题在于字符串的连接。在PHP中,您可以通过多种方式完成此操作

从PHP 5.6.0开始,可以在类常量的上下文中使用涉及数字和字符串文字和/或常量的标量表达式。

这意味着可以执行以下操作

const KEY ='OMDBAPIKEY';
private $_nodes = array("https://omdbapi.com/?apikey={self::KEY}&i=%s");

但这不是最干净的方式。更好的选择是将它添加到构造函数中。您可以在以下代码中看到不同类型的串联

<?php
class Test {
    private $_nodes = [];

    public function __construct(array $site_config)
    {
        // simple concatenation with .
        $this->_nodes[] = "https://omdbapi.com/?apikey=". $site_config['OMDBAPIKEY'] ."&i=%s";
        // using sprintf my prefered way, noticed escaped %s with i=
        $this->_nodes[] = sprintf("https://omdbapi.com/?apikey=%s&i=%%s", $site_config['OMDBAPIKEY']);
        // using complex curly syntax
        $this->_nodes[] = "https://omdbapi.com/?apikey={$site_config['OMDBAPIKEY']}&i=%s";
    }

    public function printNodes()
    {
        var_dump($this->_nodes);
    }
}

$t = new Test(['OMDBAPIKEY' => 'abc']);
$t->printNodes();

会打印

array(3) {
  [0]=>
  string(36) "https://omdbapi.com/?apikey=abc&i=%s"
  [1]=>
  string(36) "https://omdbapi.com/?apikey=abc&i=%s"
  [2]=>
  string(36) "https://omdbapi.com/?apikey=abc&i=%s"
}