1

When I see a 'self' automatically to think of static methods. Lately I have been pointed out that self depends on the context. Just like 'parent', which can also call static methods. Consider this example:

error_reporting(-1);

class A
{
    public $var = 1;

    public function __construct($n)
    {
        $this->var = $n;

        self::foo();
    }

    public function foo()
    {
        echo $this->var;
    }
}

$obj = new A(5);

Operate without errors and within the method foo $ this is available. Someone can tell me some guide that explains in detail how the calls are resolved by self and parent?

Federkun
  • 36,084
  • 8
  • 78
  • 90
  • 1
    http://stackoverflow.com/questions/1948315/wheres-the-difference-between-self-and-this-in-a-php-class-or-php-method – N.B. Aug 26 '11 at 09:52
  • I know the difference between self and $ this, noting that it is done in some cases self refers directly to the instance. – Federkun Aug 26 '11 at 10:00
  • 1
    Maybe the second answer at this question could help you: http://stackoverflow.com/questions/151969/php-self-vs-this – Fabrizio D'Ammassa Aug 26 '11 at 10:18

1 Answers1

2

$this $is a reference to the current object, while self is the reference to the class where it is used.

An example - the result of the code below is: (B::func)(A::func).

class A {
    function call() {
        $this->func();
        self::func();
    }

    function func() {
        echo '(A::func)';
    }
}

class B extends A {
    function func() {
        echo '(B::func)';
    }
}

$b = new B();
$b->call();
piotrp
  • 3,755
  • 1
  • 24
  • 26