我试图在一个方法中多次使用一个PHP实例变量,但只有第一个显示一个值,其余的什么都不返回。什么是正确的方法。查看示例代码
<? class Foo{
private $variable;
//constructor
public function __construct($variable){
$this->variable = $variable;
}
//method
public function renderVariable(){
echo "first use of the variable".$this->variable; //shows the variable when method is called
echo "subsequent use of the variable".this->variable; //shows nothing
}
}
?>
假设上面的类另存为Foo.php并在下面调用
<html>
<head>
<title></title>
</head>
<body>
<?
include 'Foo.php';
$x = Foo(37);
$x->renderVariable();//prints two lines, the first includes 37, the second does not
?>
</body>
当前,我必须将实例传递给方法中的局部变量,请参见下文
<? class Foo{
private $variable;
//constructor
public function __construct($variable){
$this->variable = $variable;
}
//method
public function renderVariable(){
$y=$this->variable;
echo "first use of the variable".$y; //shows the variable when method is called
echo "subsequent use of the variable".$y; //shows the variable when method is called
}
}
?>