带有类定义的PHP数组声明

时间:2017-03-07 15:11:12

标签: php arrays declaration

在我的PHP代码中我收到此错误

Notice: Undefined variable: browserHeader in connectenparse.class.php on line 12

我的代码从第9行开始

private $browserHeader = array ( "'0' => Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
    public function connectenParse($loginPage, $header=''){
        $this->loginPage = $loginPage;
        $this->browserHeader = $browserHeader[$header];
    }

我的输入是

$run = new connectenParse('http://example.com','0');
echo $run->streamParser();

streamParser函数接受变量end返回它。当我使用为浏览器头定义的第二个参数创建类时,它必须返回Mozilla / 5.0。问题在哪里?

3 个答案:

答案 0 :(得分:1)

问题是您尝试访问$header数组的$browserHeader元素,而没有定义$browserHeader数组:

public function connectenParse($loginPage, $header=''){
    $this->loginPage = $loginPage;
    $this->browserHeader = $browserHeader[$header];
}

在第三行,您要为$this->browserHeader分配一个值,这非常合适,但您指定的值为$browserHeader[$header]$header存在,但是此方法不知道任何名为$browserHeader的变量,这就是您看到错误的原因。你可能意味着要做以下事情:

$this->browserHeader = $header;

答案 1 :(得分:0)

您的$browerheader变量应该是这样的

private $browserHeader = array ("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html");

如果要将$header值传递给函数调用,则应使用

$this->browserHeader = isset($this->$browserHeader[$header]) ? $this->$browserHeader[$header] : $this->$browserHeader[0];

如果$header是一个字符串,您可以像这样使用它

$this->$browserHeader = $header;

答案 2 :(得分:0)

我的建议是你不需要$browserHeader成为一个数组,它显然是一个字符串并根据需要进行设置。

private $browserHeader;
public function connectenParse($loginPage, $header=''){
    $this->loginPage = $loginPage;
    $this->browserHeader = $header;
}

然后您可以将其称为

$run = new connectenParse('http://example.com', "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");

如果你需要多个其他潜在标题的数组,那么你需要修复你的数组

const BROWSER_HEADER_LIST = array ("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");

注意它不是(“0 => ...”)使它成为值的一部分。它也是一个const意味着你在需要时使用它。

所以现在你可以做这样的事情

//Still have this variable
private $browserHeader;
//use numbers not strings for $header.
public function connectenParse($loginPage, $header=null){
    $this->loginPage = $loginPage;

    if($header !== null){
        $this->browserHeader = self::BROWSER_HEADER_LIST[$header];
    }
}

另外,connectenParse可能应该是__construct($loginPage, $header)不推荐使用类名构造函数。

相关问题