Page 1 of 1

parent::func() or $this->func()

Posted: Fri Sep 23, 2005 2:38 am
by Ree
Both of these echo the same message:

Code: Select all

class Test
{
  function echoTest()
  {
    echo 'I am Test.';
  }
}

class Tester extends Test
{
  function echoTester()
  {
    parent::echoTest();
  }
}

$tester = &new Tester();
$tester->echoTester();

Code: Select all

class Test
{
  function echoTest()
  {
    echo 'I am Test.';
  }
}

class Tester extends Test
{
  function echoTester()
  {
    $this->echoTest();
  }
}

$tester = &new Tester();
$tester->echoTester();
Why do they have 'parent::' then? When will I want to use it instead of '$this->'?

Posted: Fri Sep 23, 2005 7:43 am
by Chris Corbyn
In static method/properties. self::method() points to a static method in the current class too.

Posted: Sat Sep 24, 2005 3:32 pm
by Ree
Yeah, but back to my question, what's the difference between parent::method() and $this->method()? When will I want to use one and not another? Or is there absolutely no difference at all?

Posted: Sat Sep 24, 2005 4:08 pm
by feyd
using "parent" will directly call the parent of the class you are currently in, while using $this may call something at your current depth as opposed to your parent. "self" is correctly used to call a static function or variable of the current class, wherever it resides (lineage-wise) unless you aren't given access to it, via an access modifier such as "private"