【问题标题】:How to access a class variable inside a function with PHP如何使用 PHP 访问函数内部的类变量
【发布时间】:2016-08-16 20:52:10
【问题描述】:

我在一个类中将几个函数组合在一起。一些函数将使用相同的列表来完成一些计算工作。有没有办法放置列表,以便所有函数仍然可以访问列表,而不是将列表放在需要列表的每个函数中?

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

【问题讨论】:

    标签: php class oop


    【解决方案1】:

    删除 $ 第 8 行。您在访问类中的变量。在类中,您可以像这样调用方法和变量:$this->myMethod()$this->myVar。在类之外调用方法和变量,如$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();
    

    【讨论】:

      【解决方案2】:

      您正在尝试access an object member,因此您应该使用$this->classArray。如果那里有美元符号,$classArray(未定义)将被评估。

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

      所以:删除美元符号。 :-)

      【讨论】:

        猜你喜欢
        • 2014-04-08
        • 1970-01-01
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 2023-03-12
        • 2015-04-29
        • 2017-02-02
        相关资源
        最近更新 更多