Linked by John Collins on Wed 21st Apr 2004 06:42 UTC
General Development The purpose of this article is to give a novice programmer the basic idea of what OOP is, as implemented using PHP. Readers should have a basic knowledge of programming ie what variables are, variable types, basic methods of writing comments, and how to enter code into a text editor.
Permalink for comment
To read all comments associated with this story, please click here.
Errors in Article
by Xavier on Wed 21st Apr 2004 14:58 UTC

If you declare a property in your class such as var $Gender; then you must access it through $this->Gender or $object->Gender, not $this->$Gender or $object->$Gender
If $Gender is a local variable and has a value, (say, "name"), accessing $this->$Gender will effectively access $this->name.

Say for example I do this:

class Student {
var $gender;
var $name;

function blah() {
$Gender = "name";
$this->$Gender = "Male";
echo "Gender: " . $this->$Gender; // Will print "Male" indeed.
}

}

$s =& new Student;
$s->blah(); // will print "Male"
echo $s->gender; // Will not print anything
echo $s->$Gender; // Will not print anything
echo $s->Name; // Will print "Male";

The lesson here is that you should never use the dollar sign to refer to an object's property. Whether it is to set it, or to retrieve it.

The article uses them for every single property and this is not the proper way to refer to instance variables at all.

The proper way would be as follow:

class Student {
var $gender;
var $name;

function blah() {The article
$this->name = "Blah!";
$this->gender = "Male";
echo "Gender: " . $this->gender; // Will print "Male"
}
}

$s =& new Student;
$s->blah(); // Will print "Gender: Male";
echo $s->gender; // Will print "Male";
echo $s->name; // Will print "Blah!";

This process is also highlighted all over the place in the php documentation.

I think an errata is required here.