subscribe: Posts | Comments

Classes (Objects) in php

0 comments


To declare an object in PHP using the construction class the instance
variables are declared putting var name and member functions defined within the
block of the class as ordinary functions. A constructor is defined as a function
with the same name as the object.

To refer to the object or member variables, we use $this->

An example of the above would be:
class MyObject (
var $ nCount = 0;
var $ strName;
function MyObject ($ strName = "noname") (
$ this-> strName = $ strName;
)
AddCount function ($ nDelta) (
$ this-> nCount + = $ nDelta;
)
function GetCount () (
return $ this-> nCount;
)
)
As we see, in the function member can use default settings and anything else you
would use a normal function.

To use this object, do:
$ MyObj = new MyObject ( "Pepito");
Echo ( "Count goes". $ MyObj-> GetCount (). "<BR>);
$ MyObj-> AddCount (5);
Echo ( "Now count goes." $ MyObj-> GetCount ());
Very careful with uppercase and lowercase letters in the names of the variables
of type object, because the PHP tends to be case sensitive with them.