简体   繁体   English

如何使用PHP访问函数内部的类变量

[英]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. 删除$行。8.在类中访问变量。 Inside the class you call methods and variables like so: $this->myMethod() and $this->myVar . 在类中,您可以像这样调用方法和变量: $this->myMethod()$this->myVar Outside the Class call the method and var like so $test->myMethod() and $test->myVar . 在类外部调用方法和变量,例如$test->myMethod()$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 . 您正在尝试访问对象成员 ,因此应使用$this->classArray If you have the dollar sign there, $classArray (which isn't defined) would be evaluated. 如果那里有美元符号, $classArray评估$classArray (未定义)。

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. 例如,如果你把$classArray = 'test' ,与启动前行$firstFive = ,PHP将试图访问测试员,并说,它不存在。

So: Remove the dollar sign. 因此:删除美元符号。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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