繁体   English   中英

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

[英]How to access a class variable inside a function with 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 在类外部调用方法和变量,例如$test->myMethod()$test->myVar

注意,方法和变量都可以定义为私有或公共。 这样一来,您便可以在课程之外访问它们。

// 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->classArray 如果那里有美元符号, $classArray评估$classArray (未定义)。

例如,如果你把$classArray = 'test' ,与启动前行$firstFive = ,PHP将试图访问测试员,并说,它不存在。

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

暂无
暂无

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

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