I'm having trouble accessing a class' variable.
I have the functions below in the class.
class Profile {
var $Heading;
// ...
function setPageTitle($title)
{
$this->Heading = $title;
echo 'S: ' . $this->Heading;
}
function getPageTitle2()
{
开发者_JAVA百科 echo 'G: ' . $this->Heading;
return $this->Heading;
}
// ...
}
Now when I run the method $this->setPageTitle("test")
I only get
G: S: test
What's wrong with the getPageTitle2
function? Heading is public btw. Please help!
Thanks guys!
Now when I run the method
$this->setPageTitle("test")
I only get
G: S: test
That sounds implausible. Are you sure you're not running:
$this->getPageTitle2();
$this->setPageTitle("test");
PHP - like most programming languages - is an imperative language. This means that the order in which you do things matters. The variable $this->Header
is not set at the time where you call getPageTitle2
.
If you have "G: S: test" it means you called getPageTitle2 before setPageTitle ! It looks normal then : I suggest first set then get.
you have to declare the Heading and title out of the function ... i dont know if you already did that
see the order of calling the functions
class Profile {
var $Heading;
// ...
function setPageTitle($title)
{
$this->Heading = $title;
echo 'S: ' . $this->Heading;
}
function getPageTitle2()
{
echo 'G: ' . $this->Heading;
return $this->Heading;
}
// ...
}
I am guessing you are doing something like this:
$profile = new Profile();
$profile->setPageTitle("test");
$profile->getPageTitle2();
and that this would result in the following output:
S: testG: test
and that if you echo $profile
you will just get
test
so what do you think is the problem or what are you not accomplishing that you want to?
also I would probably declare $Heading
as
private $heading;
精彩评论