Page 1 of 1

New to PHP, problem with classes

Posted: Tue May 20, 2008 8:26 am
by scottrick49
Hi,

I have just started learning some PHP. I have alot of experience with c/c++ and java, but wanted to learn about this "php thing" i keep hearing about.

I'm trying to create an object which has five values in it. However, I must be doing something wrong syntactically becaue the output isn't what I expect. Either I am assigning the variables incorrectly in the constructor, or I am not displaying them correctly, because my output isn't what I expect.

The class definition:

Code: Select all

        class record
        {
            var $name;
            var $score;
            var $hits;
            var $shots;
            var $date;
            
            function record($newName, $newScore, $newHits, $newShots, $newDate)
            {
                $this->$name    = $newName;
                $this->$score   = $newScore;
                $this->$hits    = $newHits;
                $this->$shots   = $newShots;
                $this->$date    = $newDate;
            }
            
            function recordEcho()
            {
                echo "RECORD=" . $this->$name . "  " . $this->$score . "  " . $this->$hits . "  " . $this->$shots . "  " . $this->$date . "<br>";
            }
        }
Where I create the class:

Code: Select all

echo "NAME  = " . $submittedName . "<br>";
echo "SCORE = " . $submittedScore . "<br>";
echo "HITS  = " . $submittedHits . "<br>";
echo "SHOTS = " . $submittedShots . "<br>";
echo "DATE  = " . $submittedDate . "<br>";
 
$newRecord = new record($submittedName, $submittedScore, $submittedHits, $submittedShots, $submittedDate);
$newRecord->recordEcho();
And then what actually gets output:

Code: Select all

NAME = scottrick
SCORE = 4949
HITS = 15
SHOTS = 27
DATE = 568798
RECORD=568798 568798 568798 568798 568798
While I was expecting something like:

Code: Select all

RECORD=scottrick 4949 15 27 568798
Does anybody know what am I doing wrong? Thanks!

Re: New to PHP, problem with classes

Posted: Tue May 20, 2008 10:00 am
by scottrick49
Figured it out:

Code: Select all

function record($newName, $newScore, $newHits, $newShots, $newDate)
            {
                $this->$name    = $newName;
                $this->$score   = $newScore;
                $this->$hits    = $newHits;
                $this->$shots   = $newShots;
                $this->$date    = $newDate;
            }
should be:

Code: Select all

function record($newName, $newScore, $newHits, $newShots, $newDate)
            {
                $this->name    = $newName;
                $this->score   = $newScore;
                $this->hits    = $newHits;
                $this->shots   = $newShots;
                $this->date    = $newDate;
            }
and a similar change to the echoRecord function. I only need one dollar sign when referencing a variable.

A moderator can close this topic.