Fearghal
Fearghal

Reputation: 263

PHP Class variable access question

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()
    {       
        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!

Upvotes: 0

Views: 1645

Answers (4)

kelly
kelly

Reputation: 1

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;

Upvotes: 0

Hiyasat
Hiyasat

Reputation: 8926

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

Upvotes: 0

troelskn
troelskn

Reputation: 117427

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.

Upvotes: 4

Eric
Eric

Reputation: 5331

If you have "G: S: test" it means you called getPageTitle2 before setPageTitle ! It looks normal then : I suggest first set then get.

Upvotes: 1

Related Questions