2010-11-10 87 views
0

我有这个类,我想从Gettest方法中获得第二个方法runSecond中的值。我会怎么做?如何访问方法的变量

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

说真的。别。停止。问问你自己想要什么。然后做一个理智的方式。 (我会建议只将值传递给'runSecond',而是一个类*成员变量* - 参见[类和对象](http://php.net/manual/en/language.oop5.php) - 是另一种可能适用的方法 - 但在这个有限的上下文中看起来令人怀疑。) – 2010-11-10 18:52:29

+0

我想学习如何访问类memeber变量? – Autolycus 2010-11-10 18:53:33

+0

可能重复[访问变量从另一个函数的作用域?](http://stackoverflow.com/questions/1699117/access-variable-from-scope-of-another-function) – outis 2012-02-13 12:50:59

回答

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::的原始方式也无法调用非静态方法。

+0

我想知道如何访问变量中的变量? – Autolycus 2010-11-10 18:56:54

+0

上面的解决方案没有工作...同样的错误 – Autolycus 2010-11-10 19:19:18

+0

我解决了这个问题。要使用成员变量,需要使用引用当前对象的'$ this->',而不是引用该类的'self ::'。我仍然不明白为什么你不想仅仅使用参数。 – 2010-11-10 19:38:49