2017-03-07 61 views
0

在我的PHP代码中,我得到这个错误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函数采用变量结束返回它。当我使用为浏览器头部定义的第二个参数创建类时,它必须返回Mozilla/5.0。哪里有问题?

+0

你要'$ this-> browserHeader = $ header;'? – nerdlyist

+0

[PHP:“Notice:Undefined variable”,“Notice:Undefined index”和“Notice:Undefined offset”](http:// stackoverflow。com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) –

+0

@nerdlyist现在它返回'0',而不是浏览器标题 –

回答

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 => ...“),这使它成为价值的一部分。此外,它是一个常量,意味着您在需要时使用它。

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

//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)类名构造已被弃用。

+0

最好的解决方案,我曾经读。谢谢你,谢谢你,让我的一天:) –

1

的问题是,你正在试图访问$browserHeader阵列的$header元件,而没有限定$browserHeader数组:

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

在要到$this->browserHeader分配值的第三行,这是完全很好,但你分配的价值是$browserHeader[$header]$header存在,但是此方法不知道任何称为$browserHeader的变量,这就是您看到该错误的原因。你可能说到做到,而不是执行以下操作:

$this->browserHeader = $header;

+0

它返回'0',我不得不采取Mozilla/5.0头。当我创建与第二个参数定义为浏览器头的类,它必须返回Mozilla/5.0 –

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;