注意:未初始化字符串偏移量


Notice: unintialized string offset

我在下面有以下代码,它工作得很好 - 但现在当我报告所有错误时 - 我可以看到这个:

注意:未初始化的字符串偏移量:9 英寸 C:''xampp''htdocs''website''dev''lib''player.class.php 在第 110 行 通知: 未初始化的字符串偏移量:10 英寸 C:''xampp''htdocs''website''dev''lib''player.class.php 在第 110 行 通知: 未初始化的字符串偏移量:11 英寸 C:''xampp''htdocs''website''dev''lib''player.class.php 在第 110 行 通知: 未初始化的字符串偏移量:12 英寸 C:''xampp''htdocs''website''dev''lib''player.class.php 在第 110 行 通知: 未初始化的字符串偏移量:13 英寸 C:''xampp''htdocs''website''dev''lib''player.class.php 在第 110 行

110路是

$this->formattedname .= "<span style='color:" . $colour . "'>" . $this->username[$i] . "</span>";

在福里奇

有谁知道我做错了什么?我无法获得修复这些错误的解决方案。:(

if ($this->admin == 1) {
            $colours = explode("~", $this->gradientcolours);
            $gradient = new ColourGradient(array(0 => $colours['0'], (strlen($this->username) - 1) => $colours['1']));
            $this->formattedname .= ($this->admin == 1) ? "<b><i><a style='text-decoration: none;' title='" . $this->title . "' href='/profile/" . $this->id . "'>" : "<b><a title='" . $this->title . "' href='/profile/" . $this->id . "'>";
            $this->formattedname2 = ($this->admin == 1) ? "<b><i><a style='text-decoration: none;' title='" . $this->title . "' href='/profile/" . $this->id . "'>" : "<b><a title='" . $this->title . "' href='/profile/" . $this->id . "'>";

                    foreach($gradient as $i => $colour) {
                $this->formattedname .= "<span style='color:" . $colour . "'>" . $this->username[$i] . "</span>";
            }
            $this->formattedname .= ($this->admin == 1) ? "</a></i></b>" : "</a></b>";
            $this->formattedname2 .= ($this->admin == 1) ? "</a></i></b>" : "</a></b>";
        }

如果以下任何变量实际上是字符串或 null 而不是数组,则会发生此错误。

尝试在使用数组之前对其进行测试和初始化

if( !isset($this->username[$i]) ) $this->username[$i] = '' ;

这不是错误,而是通知。错误或警告意味着您做错了/犯了错误。通知只是暗示某些事情可能会做得更好。

告诉你的是,你正在使用一个不存在的密钥:

$array[0] = 0;
$array[1] = 1;
$array[2] = 2;
echo $array[0]; // no notice, it exists
echo $array[2]; // no notice, it exists
echo $array[9]; // the notice will fire, because key 9 doesn't exist

在您的代码中,我无法分辨哪一行是 110,但我猜$this->username[$i]是问题所在,用户 9 到 13 不存在

如果$this->username不是数组而是字符串,它将返回第 N 个字符:

$string = "example";
echo $string[1]; // will return X, an array starts counting at 0 (zero-index-based)
echo $string[50]; // blank echo, and the notice because character 50 doesn't exist

如果对字符串使用串联.=, 您的字符串必须像这样初始化

$this->formattedname = "";

和连接后

问题出在以下行上:

$this->username[$i].

您的用户名可能有 5 个字符,而$i可以说 12 个字符。使用适当的条件进行验证。