NYCPHP Meetup

NYPHP.org

[nycphp-talk] self:: or $this ?

Dan Cech dcech at phpwerx.net
Fri Nov 9 15:51:50 EST 2007


Dan Cech wrote:
> Morgan Craft wrote:
>> Any reason why I should use $this->methodName()  over self::methodName()
>> Or is the self::methodName() reserved only for working within a static
>> method?
> 
> The deciding factor is the nature of methodName()
> 
> self::methodName() if methodName is static
> $this->methodName() if methodName is not static

One interesting twist, self::methodName is not inherited:

http://us2.php.net/manual/en/language.oop5.static.php

A simple demonstration:

<?php

class parentclass
{
	function test()
	{
		return 'parentclass';
	}
	
	function test_self()
	{
		return self::test();
	}
	
	function test_this()
	{
		return $this->test();
	}
}

class subclass extends parentclass
{
	function test()
	{
		return 'subclass';
	}
	
	function test_self_sub()
	{
		return self::test();
	}

}

$test = new subclass();

echo 'self     '. $test->test_self() ."\n";
echo 'this     '. $test->test_this() ."\n";
echo 'self_sub '. $test->test_self_sub() ."\n";

Will produce:

self     parentclass
this     subclass
self_sub subclass

So, if you are calling methodName from a non-static function and wish to
use inheritance, you should use $this->methodName(), otherwise you
cannot override methodName in a sub-class.

That said, calling a static method via $this-> or calling a non-static
method via self:: will generate an E_STRICT notice, so sticking to
calling according to the definition is definitely the best policy.

Dan



More information about the talk mailing list