PHP Encapsulation Surprises

By Angsuman Chakraborty, Gaea News Network
Thursday, September 15, 2005

In PHP, 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:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        A::foo();
    }
}

$a = new A();
$a->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.

Discussion
January 24, 2010: 9:29 am

thanks for sharing

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :