Classes and OO

CLASS#

Return the class name of the instance currently being acted on.

__CLASS__ is a compile-time-recognised token that evaluates at runtime to the class name of the invoking instance. Inside a method body or a field initializer expression (introduced by use feature 'class'), it gives the actual class of the object under construction or in use — which may be a subclass of the package the code textually lives in. Outside of class-feature code it is essentially equivalent to ref($self), but unlike ref it is usable in a field initializer, where $self is not yet bound.

Synopsis#

use feature 'class';

field $x = __CLASS__->DEFAULT_X;        # in a field initializer
method m { return __CLASS__; }          # in a method body

What you get back#

A plain string: the name of the class of the invoking instance. The value is the same kind of string ref returns for a blessed reference. It is not a reference; call methods on it as you would on any class name.

my $name = __CLASS__;                   # e.g. "DifferentCustomField"
my $obj  = __CLASS__->new(...);         # class-method dispatch

When it differs from __PACKAGE__#

__PACKAGE__ is resolved at compile time and names the package the token textually appears in. __CLASS__ is resolved at runtime and names the class of the instance — which, for a method or field initializer inherited by a subclass, is the subclass.

use feature 'class';

class Base {
    field $f = __CLASS__->default_f;    # evaluated per instance
    sub default_f { 10 }
    method class_name { __CLASS__ }
    method pkg_name  { __PACKAGE__ }
}

class Derived :isa(Base) {
    sub default_f { 20 }
}

my $obj = Derived->new;
$obj->class_name;                       # "Derived"
$obj->pkg_name;                         # "Base"
# $f was initialised to 20, not 10, because __CLASS__ dispatched
# through the Derived package.

In a non-inherited context (no subclassing involved), __CLASS__ and __PACKAGE__ yield the same string.

Examples#

Class method invoked from a field initializer — the canonical use case. Without __CLASS__, a subclass cannot override the default:

use feature 'class';

class WithCustomField {
    use constant DEFAULT_X => 10;
    field $x = __CLASS__->DEFAULT_X;
}

class DifferentCustomField :isa(WithCustomField) {
    sub DEFAULT_X { rand > 0.5 ? 20 : 30 }
}

my $obj = DifferentCustomField->new;    # $x is 20 or 30, not 10

Inside a method body, equivalent to ref $self:

class Logger {
    method log ($msg) {
        print STDERR "[", __CLASS__, "] $msg\n";
    }
}

Constructing a fresh instance of the same class as the invoking object — useful for clone-like factory methods that must respect subclasses:

class Node {
    field $label :param;
    method spawn ($child_label) {
        return __CLASS__->new(label => $child_label);
    }
}

Comparison with __PACKAGE__ for diagnostics that want to pin the exact dispatch target:

class Thing {
    method describe {
        return sprintf "defined in %s, dispatched as %s",
            __PACKAGE__, __CLASS__;
    }
}

Edge cases#

  • Only valid under use feature 'class' inside a method body, a field initializer, or another class-feature construct (for example ADJUST blocks). Using it outside such a context is a compile-time error.

  • No parentheses, no arguments. __CLASS__ is a bareword token, not a function call. __CLASS__() is a syntax error.

  • Not the same as ref $self during field initialization — $self is not yet bound while fields are being set, so ref $self is unavailable. __CLASS__ is the only way to reach the instance’s class from inside a field initializer.

  • Not ref for a class method call. When called as a class method (no instance in hand), __CLASS__ yields the class the method was invoked on, not the package the method was defined in. This mirrors normal method dispatch.

  • String, not reference. Method calls via __CLASS__->... are class-method dispatches, not instance-method dispatches. The method will not see a blessed reference as its invocant.

  • The class feature is marked experimental in Perl 5.42; it emits a experimental::class warning unless silenced with no warnings 'experimental::class'.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • __PACKAGE__ — compile-time package name of the surrounding code; use this when you want the textual package, not the runtime class

  • ref — runtime class name of a blessed reference; use this when you already hold an instance and are not inside a field initializer

  • bless — associate a reference with a class name; the low-level primitive that __CLASS__-style dispatch ultimately resolves against

  • isa — test whether the current class is a subclass of a given name; pairs naturally with __CLASS__ for runtime checks

  • sub — declares subroutines, including the method form that makes __CLASS__ meaningful