Wednesday, December 9, 2009

Public, Protected, and Private Properties

When defining a class member in the class definition, the developer
needs to specify one of these three access modifiers before declaring the member
itself. In case you are familiar with PHP 3 or 4’s object model, all class
members were defined with the var keyword, which is equivalent to public in
PHP 5. var has been kept for backward compatibility, but it is deprecated,
thus, you are encouraged to convert your scripts to the new keywords:
class MyClass {
public $publicMember = "Public member";
protected $protectedMember = "Protected member";
private $privateMember = "Private member";
function myMethod(){
// ...
}
}
$obj = new MyClass();


#Public members can be accessed both from outside an object by
using $obj->publicMember and by accessing it from inside the myMethod
method via the special $this variable (for example, $this->publicMember).
If another class inherits a public member, the same rules apply, and it
can be accessed both from outside the derived class’s objects and from
within its methods.
#Protected. Protected members can be accessed only from within an
object’s method—for example, $this->protectedMember. If another class
inherits a protected member, the same rules apply, and it can be accessed
from within the derived object’s methods via the special $this variable.
#Private. Private members are similar to protected members because they
can be accessed only from within an object’s method. However, they are
also inaccessible from a derived object’s methods. Because private properties
aren’t visible from inheriting classes, two related classes may
declare the same private properties. Each class will see its own private
copy, which are unrelated.

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off