|
Well, a class is more or less a stamp, or a forming block, it is the basis from which objects can be generated thus; you may see it as a template. You see, object oriented people didn’t like much the layout of traditional procedural programming and they created a bunch of buzz words. They took groups of normal procedures, they incorporated variables into theses groups and then they exclaimed “this is the way to form new data types, long live the class”. According to their opinion they managed to imitate real world concepts and objects. All these ideas are a bit debatable but I wouldn’t start the third world war here and the truth is object oriented programming is very programmer friendly. OK, so a class is a prototype containing properties (variables) and methods (procedures). All objects created from a class inherit the class’s properties and methods. In other terms you may instantiate a class many times on the fly (without feeling any guilt about system resources) and generate objects with similar characteristics. Here follows an example of a class: <? class user { ### properties var $name; var $username; var $email; var $id=0; var $loggedin; ### methods function setname($newname) { $this->name = $newname; } function getname() { return $this->name; } function setid($lastid) { $this->id = ++$lastid; } function hello() { print "Hello"; } } # create a new user $admin = new user(); # set its name and then print it # demonstrating direct access of its properties $admin->name = harris; print "\n$admin->name"; # \n is the new line character # repeat but this time use class methods $admin->setname("murray"); print "\n" . $admin->getname(); # functions are not evaluated inside quotes # use another method $admin->setid(0); print "\n$admin->id"; ### another user object $auser = new user(); $auser->setname("gers"); $auser->setid($admin->id); print "\n$auser->name $auser->id\n"; ### access a class method directly print user::hello(); ?> I think the code is pretty much easy to follow, just to say, that instead of accessing member properties directly it is a good practice to have setter and getter methods. |