A CCESSING M ETHODS AND P ROPERTIES U SING THE $this VARIABLE

chinmay.sahoo

New member
During the execution of an object’s method, a special variable called $this is automatically defined, which denotes a reference to the object itself. By using this variable and the -> notation, the object’s methods and properties can be
further referenced. For example, you can access the $name property by using $this->name (note that you don’t use a $ before the name of the property). An object’s methods can be accessed in the same way; for example, from inside one
of person’s methods, you could call getName() by writing $this->getName() .

A key paradigm in OOP is encapsulation and access protection of object properties (also referred to as member variables). Most common OO languages have three main access restriction keywords: public, protected, and private.

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();


This example will be built upon to demonstrate the use of these access modifiers.
 
Back
Top