How should I share / pass variables across different methods in a PHP Class?
I am trying to set a value from a method of a class and trying to get it in another method. The example code is as below. I think the below kind of set/get works in a Java cla开发者_如何学Css. Googled out but still could not find a relevant solution.
I searched for "how to share data across functions in PHP" and found How can I call member variables of a class within a static method?, but that did not answer my question.
<?php
class MyClass
{
public $cons;
function showConstant() {
$this->setConstant(100); /* assign value to variable here */
$this->showConstantGetter();
}
/* setter */
function setConstant($aCons) {
$cons = $aCons;
}
/* getter */
function getConstant() {
return $cons;
}
function showConstantGetter() {
echo "<br>getting const : ".$this->getConstant(); /* use the variable's value in this method here */
}
}
$classname = "MyClass";
$class = new MyClass();
$class->showConstant();
?>
You must use $this->cons
instead of $cons
, that's all.
Nearly good but:
function setConstant($aCons) {
$this->cons = $aCons;
}
/* getter */
function getConstant() {
return $this->cons;
}
To access instance variables in PHP, you need to prefix them with $this->
.
In your example:
function getConstant() { return $this->cons; }
To access a class (or static) variable, you use self::
instead of $this->
.
Note that it is this:
$this->cons = $aCons;
and not this:
$this->$cons = $aCons;
If you specify $this->$cons
, PHP will first look at the value in $cons
and uses that as the name of the instance variable. In your case, there is nothing in $cons
yet, so it will find a name that is empty, which causes the error message.
This type of indirection is not what you want to do here, so don't put the dollar sign in there twice!
Hi Thanks for the answers. That was a very quick resolution. Appreciate it very much. Thanks everyone and all. Here is the complete code which works:
<?php
class MyClass
{
var $cons;
function showConstant() {
$this->setConstant(100); /* assign value to variable here */
$this->showConstantGetter();
}
/* setter */
function setConstant($aCons) {
$this->cons = $aCons;
}
/* getter */
function getConstant() {
return $this->cons;
}
function showConstantGetter() {
echo "<br>getting const : ".$this->getConstant(); /* use the variable's value in this method here */
}
}
$classname = "MyClass";
$class = new MyClass();
$class->showConstant();
?>
精彩评论