我是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()时,它在我的页面中返回空白,任何想法?
答案 0 :(得分:2)
将变量设为公共变量,在class Sample {
之后声明,并且可以在类中的任何位置使用它们。
答案 1 :(得分: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;
}
}
答案 2 :(得分: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;
}
}