Cannot use [] for reading

▼魔方 西西 提交于 2019-12-17 18:34:10

问题


In one of my scripts, I try to do the following

$data[] = self::get($row['sr_id']); // <-- line 55

However, PHP does not allow me to do this, giving me this error

Fatal error: Cannot use [] for reading in /file.php on line 55

The self::get function return either a bool, or an object.

Edit: The get function creates a new object which again loads data from a mysql database.


回答1:


Old PHP versions accepted $var[] in expressions, allowed reading out the $var content regardless of syntax. PHP 5.1 made that illegal. But sometimes the error is triggered outside of the intented context.
So my guess (again: show more code) is that the preceeding line contains an unfinished expression, to which the $data[] joins.

In case of object attribute you can wrap your $data var into { }, but that doesn't seem to be the problem in your case. (Else there is something in line 54, that you didn't show.) The right hand side can't reasonably trigger the error. Even array accessing [] an integer or object wouldn't trigger that fatal error.

So if nothing helps, just use array_push(). Work around PHP.




回答2:


The solution in my case was this:

  • Bad line:

$this->$ExtraTag[] = $fullscript;

  • Good line:

$this->{$ExtraTag}[] = $fullscript;

or

$this->ExtraTag[] = $fullscript;




回答3:


The error I got was:

Fatal error: Cannot use [] for reading in /pathtosite/drupal/sites/all/themes/zenui/templates/page.tpl.php on line 33

Sometime the problem is when you include a line like this:

$page['sidebar_first'][]

This might happen if you are copying a variable name and forgot to comment out the line.

There was two problems:

1. Missing semicolon

2. $variable[] must set a variable

After fixing these two problems my code read:

$page['sidebar_first'][] = $value;

Don't forget to comment out line you are not using to help with the debugging process

Hope this helps fellow programmers like me!




回答4:


try:

$data = Array();
$data[] = self::get($row['sr_id']); // <-- line 55



回答5:


I had the same problem with my script, the following line threw the same error:

$array[]=$value

I simply replaced it by

$array[count($array)-1]=$value

and it worked perfectly.




回答6:


Another possible problem could be an accidental double ==. For example accidentally doing $myArray[] == $myNewValue; would cause this error (because you are trying to read a value with the == instead of telling PHP to assign a new array index).




回答7:


I had same error with following:

echo implode(',', $array[]);

which should have been

echo implode(',', $array);

Hope this can help someone



来源:https://stackoverflow.com/questions/3820258/cannot-use-for-reading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!