1

我是 PHP OOP 的新手,如何在类内的函数之间共享或传递变量?

class Sample {

    public function One() {

         $var1 = 'abc';
         $var2 = 'xyz';

        return $var1;
    }

    public function Two() {

        $var3 = $var1.$var2;

        return $var3;
    }

}

还是可以返回多个值?

谢谢。

更新

class Sample {

// This is how you declare class members
public $var1, $var2;

public function One() {

     // You use $this to refer class memebers
     $this->var1 = 'abc';
     $this->var2 = 'xyz';

    return $this->var1;
}

public function Two() {

    $var3 = $this->var1.$this->var2;

    return $var3;
}

}

$test = new Sample();
echo $test->Two();

我已经测试了一个提供的示例,当调用函数 Two() 时它在我的页面中返回空白,知道吗?

4

3 回答 3

2

使变量成为公共变量,在之后声明class Sample {,它们可以在类内的任何地方使用。

于 2012-12-20T09:34:11.497 回答
2

在类中声明变量并使用 $this 访问变量

class Sample {
    public $var1;
    public $var2;

    public function One() {
        $this->var1 = 'abc';
        $this->var2 = 'xyz';
        return $this->var1;
    }

    public function Two() {
        $var3 = $this->var1.$this->var2;
        return $var3;
    }
}
于 2012-12-20T09:35:53.810 回答
1
class Sample {

    // This is how you declare class members
    protected $var1, $var2;

    public function One() {

         // You use $this to refer class memebers
         $this->var1 = 'abc';
         $this->var2 = 'xyz';

        return $this->var1;
    }

    public function Two() {

        $var3 = $this->var1.$this->var2;

        return $var3;
    }

}
于 2012-12-20T09:37:35.697 回答