John Doe
John Doe

Reputation: 1

Accessing an array that is not inside class

I'd like to access an array which does not exist inside my Class, it seems like I can seems to do it, here's an example:

    $chiInfo =
            array(
                 array("Home", "#"),
                 array("Test", "#"),
            );


    class chiBar {

        var $chiDet;
        function __construct($chiName)
        {
            $this->chiDet = $chiName;
        }

        function getArrayData($array, $arrayNumber, $arrayType, &$result) // $arrayType : 1 - Non-multi, 2 - Multi
        {
            if(!is_array($array)) 
                return 0;

            if($arrayType == 1)
                return 0;
            else
            {
                if($arrayNumber > sizeof($array)-1)
                {
                    print("Invalid array number!"); 
                    return 0;
                }

                $result = array(strval($array[$arrayNumber][0]), strval($array[$arrayNumber][1]));
            }

        }

        function addToHeader($array, $addName, $addLink)
        {   
            array_push($chiInfo, array($addName, $addLink)); // That is the link

            echo "<META HTTP-EQUIV='refresh' CONTENT='15; URL=index.php'>"; 
        }
    }

Whenever I do a different piece of code, it seems like the array is not found, error:

Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\NewTest\navClass.php on line 40

Upvotes: 0

Views: 39

Answers (2)

faintsignal
faintsignal

Reputation: 1836

If you would like to access a variable directly from your "top-level" code inside a function or class method, you must declare the variable global inside the function or method.

E.g.

...

        function addToHeader($array, $addName, $addLink)
        {   
            global $chiInfo;
            array_push($chiInfo, array($addName, $addLink)); // That is the link

            echo "<META HTTP-EQUIV='refresh' CONTENT='15; URL=index.php'>"; 
        }
...

However, you may consider adding an extra parameter to your method instead, as globals can get tricky in some contexts. You can find out more about using globals here: http://php.net/manual/en/language.variables.scope.php

The same method using a parameter instead:

...
// note the ampersand on the parameter because you seem to want to change the original variable, not just a copy of it
        function addToHeader($array, $addName, $addLink, &$chiInfo) 
        {   
            array_push($chiInfo, array($addName, $addLink)); // That is the link

            echo "<META HTTP-EQUIV='refresh' CONTENT='15; URL=index.php'>"; 
        }
...

Upvotes: 0

John Conde
John Conde

Reputation: 219804

Just pass that array as a parameter to the method:

function addToHeader($chiInfo, $array, $addName, $addLink)

And then when you call it:

$chiBar = new chiBar($chiName);
$chiBar->addToHeader($chiInfo, $array, $addName, $addLink);

Upvotes: 1

Related Questions