如何访问方法的变量

Aut*_*cus 0 php

我有这个类,我想runSecondGettest方法中获取第二个方法中的值.我该怎么办?

 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)
    }
 }
Run Code Online (Sandbox Code Playgroud)

Ala*_*nse 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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