开发者

How to create Globals Array

How do you create an array in GLOBALS for php?

for example, I want to do something like this:

$GLOBALS["chapter_names"] = array();

and then

$GLOBALS["chapter_names开发者_高级运维"][$i] = $row -> CHAPTER_NAME;

inside a while loop

where $i is the index of the array

is this the optimal way to do things?

thanks!


$GLOBALS["chapter_names"] = array();
foreach ($rows as &$row) {
    array_push($GLOBALS["chapter_names"], $row->CHAPTER_NAME);
}


Pretty much exactly as you gave it there. Except you don't need to put an index of $i when you're adding new stuff, unless it needs some specific index. You could just do it something like this:

$GLOBALS['chapter_names'] = array();
$GLOBALS['chapter_names'][] = $row -> CHAPTER_NAME;


print_r($GLOBALS);


That should work.

$GLOBALS["chapter_names"] = array();

$row = new StdClass;

$row->CHAPTER_NAME = 'test';

$i = 0;

$GLOBALS["chapter_names"][$i] = $row -> CHAPTER_NAME;

var_dump($GLOBALS);

Amongst other things, the value is displayed...

["chapter_names"]=>
  array(1) {
    [0]=>
    string(4) "test"

However, as you are probably aware, variables should only have as much scope as required, to prevent clashes and possible problems. Therefore, global variables should be avoided in most scenarios.


Don't use $GLOBALS, it's an outdated and quite dangerous practice. You can read about the Registry pattern - it's an OO solution to the problem. As for your example, it should be completely working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜