2017-03-07 50 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;