php - Setting up global array (outwith class)

734

I have a few classes (in separate files, eg /classes/admin.class.php), and I'd like them to have access to a global array, which is loaded in the main file (index.php).

I want the contents of the global array to be$cq->fetch_assoc().

How do I do this? I've read up about it, but I simply cannot get my head around it.

$GLOBALS seems to work, but is that not an outdated version (like$HTTP_POST_ARRAY?)

Thanks in advance

493

Answer

Solution:

Any variable you declare in the index.php file will be available to all the subsequently included files. However, once you go into a function definition, that variable won't be available. You can make it available by using the "global" keyword.

For example:

index.php

<?php
   $var = $cq->fetch_assoc();
?>

/classes/admin.inc.php

<?php
echo $var; //Will work!

function foo() {
    global $var;

    echo $var; //Won't work without global keyword!
}
289

Answer

Solution:

$GLOBALS seems to work, but is that not an outdated version (like$HTTP_POST_ARRAY?)

No, that are two different things.$GLOBALS is not outdated, but the superglobal variable that gives you access to the global variable table in PHP.

$HTTP_POST_ARRAY is outdated, because you should use$_POST instead.

People are also looking for solutions to the problem: php - Serialization with variable transfer to another database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.