Google

Saturday, June 7, 2008

PHP5 Encapsulation Surprises to you ..........

In PHP5, unlike Java or C++, $this has to be explicitly used to refer to variables within a

class.

The value of $this is determined by the context in which it is called. In certain situations

$this may actually refer to the invoking class rather then the current class. This breaks object

encapsulation.

$this pseudo-variable is not defined if the method in which it is located is called statically

with an exception as noted below.

$this is defined if a method is called statically from within another object. In this case, the

value of $this is that of the calling object.

The following example from PHP manual will clarify this:

foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

Output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

No comments: