Pages

Monday, February 27, 2012

what is $this in php?

$this refers to the current object. the variable is only ever used in object-oriented PHP and can't be overwritten in the global scope. 

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

class B
{
    function bar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
 

No comments:

Post a Comment

Thank you for your Comment....