我得到一个奇怪的PHP错误后更新我的PHP版本到5.4.0-3。

我有这样一个数组:

Array
(
    [host] => 127.0.0.1
    [port] => 11211
)

当我试图像这样访问它时,我会得到奇怪的警告

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];


 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...

我真的不想只是编辑我的php.ini并重新设置错误级别。


当前回答

请尝试这种方式....我已经测试了这个代码....它的工作原理……

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);

其他回答

请尝试这种方式....我已经测试了这个代码....它的工作原理……

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);

从PHP 5.4开始,我们需要传递与函数预期相同的数据类型值。例如:

function testimonial($id); // This function expects $id as an integer

当调用这个函数时,如果一个字符串值是这样提供的:

$id = $array['id']; // $id is of string type
testimonial($id); // illegal offset warning

这将生成一个非法偏移警告,因为数据类型不匹配。为了解决这个问题,你可以使用settype:

$id = settype($array['id'],"integer"); // $id now contains an integer instead of a string
testimonial($id); // now running smoothly

在我的情况下:在获取数据库记录时,确保使用 result_array ();而不是row();或row_array ();

这个问题有点晚了,但对于其他正在搜索的人来说:我通过使用错误的值(类型)初始化得到了这个错误:

$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset

正确的做法是:

 $varName = array();
 $varName["x"] = "test"; // works

为PHP

//Setup Array like so
$memcachedConfig = array(
  "host" => "127.0.0.1",
  "port" => "11211"
);

//Always a good practice to check if empty

if(isset($memcachedConfig['host']) && isset($memcachedConfig['port'])){

    //Some codes

    print_r ($memcachedConfig['host']);
    print_r ($memcachedConfig['port']);

}

只要确保返回的值不为空。 这个例子是PHP的看看如何在其他语言中检查数组是否为空。