Я пытаюсь использовать переменную экземпляра 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
}
}
?>