多次使用PHP实例变量的正确方法是什么
我试图在一个方法中多次使用一个PHP实例变量,但只有第一个实例显示一个值,其余的实例不返回任何值。正确的方法是什么。参见示例代码多次使用PHP实例变量的正确方法是什么,php,instance-variables,Php,Instance Variables,我试图在一个方法中多次使用一个PHP实例变量,但只有第一个实例显示一个值,其余的实例不返回任何值。正确的方法是什么。参见示例代码 <? class Foo{ private $variable; //constructor public function __construct($variable){ $this->variable = $variable; } //method public function renderVariable(){
<? 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
}
}
?>
第二个实例可能会失败,因为在“echo”变量的后续使用中,this
前面缺少了$
`typothis
应该是$this
是的,我看到了这个错误,但是原始代码有$Second'typo',这是你将类Foo
实例化为一个函数,也就是说,你正在调用Foo(37)代码>,而它应该是新的Foo(37)代码>。我用正确的语法复制了输出:第一次使用variable37,随后使用variable37
,正如预期的一样。谢谢Lovelace!