Asim Zaidi
Asim Zaidi

Reputation: 28284

how to access variable of a method

I have this class and I want to get the values in second method runSecond from Gettest method. How would I do that?

 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)
    }
 }

Upvotes: 0

Views: 110

Answers (1)

Alan Geleynse
Alan Geleynse

Reputation: 25139

Why do you not want to pass the values into your second method?

Method parameters are the accepted way of doing this.

The only other option you have is to use global or member variables, but for something like this I would highly suggest parameters instead. There is no good reason I can see not to.

If you really, absolutely, have to do this (and I still don't see why), you can use a private member variable like this:

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;
    }
}

Note that you have to create an instance of the class to call the second method. Your original way of using self:: would not work to call a non static method, even if you did pass the values as parameters.

Upvotes: 5

Related Questions