简体   繁体   中英

How to access a class variable inside a function with PHP

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\..

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();

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.

Eg 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. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM