7

I have grouped a few functions together in a class. Some of the functions will be using the same list to do some computational work. Is there a way to put the list so that all the functions can still access the list instead of putting the list inside each functions that needs the list?

// Simplified version of what I am trying to do
Class TestGroup
{
    public $classArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    public function getFirstFiveElemFromArray()
    {
        $firstFive = array_slice($this -> $classArray, 0, 5, true);
        return $firstFive;
    }

    public function sumFirstEightElemFromArray()
    {
        //methods to get first eight elements and sum them up
    }

}

$test = new TestGroup;
echo $test -> getFirstFiveElemFromArray();

This is the error message I am getting:

Undefined variable: classArray in C:\wamp\www\..

2 Answers 2

4

remove the $ line 8. Your accessing a variable inside the class. Inside the class you call methods and variables like so: $this->myMethod() and $this->myVar. Outside the Class call the method and var like so $test->myMethod() and $test->myVar.

Note that both methods and variables can be defined as Private or Public. Depending on that you will be able to access them outside the Class.

// Simplified version of what I am trying to do
Class TestGroup
{
    public $classArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    public function getFirstFiveElemFromArray()
    {
        $firstFive = array_slice($this -> classArray, 0, 5, true);
        return $firstFive;
    }

    public function sumFirstEightElemFromArray()
    {
        //methods to get first eight elements and sum them up
    }

}

$test = new TestGroup;
echo $test -> getFirstFiveElemFromArray();
3

You are trying to access an object member, so you should use $this->classArray. If you have the dollar sign there, $classArray (which isn't defined) would be evaluated.

E.g. if you put $classArray = 'test' before the line that starts with $firstFive =, PHP will try to access the test member and say that it doesn't exist.

So: Remove the dollar sign. :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.