如何访问方法的变量

时间:2010-11-10 18:47:50

标签: php

我有这个类,我希望从runSecond方法获取第二个方法Gettest中的值。我该怎么做?

 class Test {
    public static function Gettest($x, $y, $z){
        $x = $x;
        $x = $x . basename($y);

        self::runSecond();  
    }

    private function runSecond(){
        //how do I access $x here? I need to know the value of $x, $y and $z here 
        // and I dont want to pass it like this  self::runSecond($x, $y, $z)
    }
 }

1 个答案:

答案 0 :(得分:5)

为什么不想将值传递给第二种方法?

方法参数是可接受的方式。

你唯一的另一个选择是使用全局变量或成员变量,但对于类似的东西,我会高度建议参数。我没有理由不去看。

如果你真的,绝对必须这样做(我仍然不明白为什么),你可以使用这样的私有成员变量:

class Test {
    private $x;
    private $y;
    private $z;

    public static function Gettest($x, $y, $z){
        $x = $x;
        $x = $x . basename($y);

        $test = new Test();
        $test->x = $x;
        $test->y = $y;
        $test->z = $z;

        $test->runSecond();  
    }

    private function runSecond(){
        $this->x;
        $this->y;
        $this->z;
    }
}

请注意,您必须创建类的实例以调用第二个方法。使用self::的原始方法无法调用非静态方法,即使您将值作为参数传递也是如此。