Re: non static function called as static one
| From: | Greg Beaver | Date: | Wed, 11 Mar 2009 23:09:25 +0000 |
| Subject: | Re: non static function called as static one | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-43329@lists.php.net to get a copy of this message | ||
Olivier Doucet wrote:
> Hi,
>
>
>> not sure if this was mentioned on the general list but, i believe what
>> youre describing is documented in the manual under php5 classes/objects ->
>> "the basics":
>>
>> http://www.php.net/manual/en/language.oop5.basic.php
>>
>> $this is a reference to the calling object (usually the object to which
>> the method belongs, but can be another object, if the method is called
>> statically <http://www.php.net/manual/en/language.oop5.static.phpo†�
>> ^bʧ¹KÕüjÉõL> from
>> the context of a secondary object).
>>
>> -nathan
>>
> I know this behaviour is fully documented, but I was more concerned about
> "is it a 'normal' behaviour ?". How can a programmer controls the class he
Yes
> wrote, and make it absolutely bugproof ? How can he detect his function was
> called in a static context and forbid it (or write specific code for) ?
You can't unless you do some obtuse kind of:
if (isset($this) && $this instanceof MyClass)
But even this results in terrible and subtle mistakes if you happen to
call a "static" method from within a method of a subclass of MyClass.
instead use
static function blah()
for static functions, and $this simply will not be available.
Don't call non-static methods statically unless you want trouble.
"static" was introduced precisely for this reason.
Trying to make functions work as both dynamic and static is a disaster,
and we have had endless intractable problems with the most prevalent
implementation of this double design in the PEAR base class,
specifically with PEAR::raiseError(). Just don't do it.
Greg