in reply to Static method vs virtual method

Static methods expect a class name as the first argument. Generally, static methods ignore the first argument because they already know which class they are in. new() is implemented by almost all packages as a static method. Static methods aren't called from an instance of an object, but instead directly from the package name:

Virtual methods or instance methods expect a reference to an object as the first argument. Static methods are class-wide; virtual methods are object-specific.

--Lakshmanan G.

The great pleasure in my life is doing what people say you cannot do.


Replies are listed 'Best First'.
Re^2: Static method vs virtual method
by przemo (Scribe) on May 09, 2009 at 12:26 UTC
    Generally, static methods ignore the first argument because they already know which class they are in. new() is implemented by almost all packages as a static method.

    Yet, because of inheritance and possibility of being called on behalf of other package, well-behaving new() shouldn't ignore the first argument. In simplified case like this:

    sub new { my ($class, %opts) = @_; my $self = { %opts }; bless $self, $class; }

      Doesn't this advice directly contradict the advice of lakshmananindia, who states that new() should be static? It seems that there is a lack of consensus on whether new() should be static or virtual. This is a real problem, because no facility is provided to force the caller to invoke new() the correct way by producing an error if the invocation is wrong.

        No. Static doesn't mean "ignoring the first argument", it means "expecting the class name as the first argument". Moreover, in Perl, you can create methods that are both static and virtual (the question is why).

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,