簡體   English   中英

PHP-陣列致命錯誤

[英]PHP - Array fatal error

我的PHP代碼中有一個關於動態數組的奇怪錯誤。

輸出的錯誤是:

Fatal error: Cannot use string offset as an array ... on line 89

這是我的代碼的一部分,它在foreach循環中,該循環遍歷數據庫中的設置:

foreach($query->fetchAll() as $row)
{
    if($site!=CURRENT_SITE_TEMPLATE)
    {
        $property = 'foreignSettings';
        $propertyType = 'foreignSettingsTypes';
    } else {
        $property = 'settings';
        $propertyType = 'settingTypes';
    }

    $this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
    settype($this->$property[$row['variable_section']][$row['variable_name']],$row['variable_type']);

    $this->$propertyType[$row['variable_section']][$row['variable_name']] = $row['variable_type'];
}

對於示例代碼, $site為“ admin”, CURRENT_SITE_TEMPLATE為“ admin”。 此外, $foreignSettings, $foreignSettingsTypes, $settings, and $settingTypes均在類范圍內定義為數組。

該錯誤在第89行上,它是:

$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];

我最初以為是因為$ property變量訪問數組,但是,這看起來像PHP文檔中的有效法律代碼( example #1 http://php.net/manual/zh/language.variables.variable.phpexample #1

對此錯誤的任何幫助將不勝感激。

謝謝

在您給出的示例中, $property是一個字符串。 然后,您嘗試將其用作數組。 字符串僅具有數字索引(如果需要用作數組)。

問題如下: $this->$property[0]表示您訪問$ property的第0位,在您的情況下,它將是字符串$ property的第一個字母。 因此,您最終得到$ this-> f或$ this-> s。

使用$this->$property[0][0]您將嘗試訪問$ property字符串的第0位的第0位,這將導致錯誤,因為您嘗試訪問char的第0位是什么。由於char不能作為數組引用,因此不可能。

您想要的是$this->{$propperty}[0][0]這意味着您嘗試訪問名稱為$ propperty的變量的第0位的第0位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM