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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

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

Post 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->'?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

In static method/properties. self::method() points to a static method in the current class too.
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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"
Post Reply