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

问题描述:

我已经将一些函数分组在一个类中。一些功能将使用相同的列表来完成一些计算工作。有没有办法将列表放到列表中,以便所有函数仍然可以访问列表,而不是将列表放入每个需要列表的函数中?如何使用PHP访问函数中的类变量

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

这是错误消息我得到:

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

删除$线8.您的访问类中的变量。在课堂内部,您可以调用如下方法和变量:$this->myMethod()$this->myVar。在类之外调用方法和var像这样$test->myMethod()$test->myVar

请注意,方法和变量都可以定义为Private或Public。取决于您可以在班级以外访问它们。

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

您正在尝试access an object member,所以你应该使用$this->classArray。如果您有美元符号,则会评估$classArray(未定义)。

E.g.如果您在以$firstFive =开头的行之前放置$classArray = 'test',PHP将尝试访问测试成员并说它不存在。

因此:删除美元符号。 :-)