Why shouldn't I use UNIVERSAL::isa?

前端 未结 7 1007
终归单人心
终归单人心 2021-02-07 07:58

According to this

http://perldoc.perl.org/UNIVERSAL.html

I shouldn\'t use UNIVERSAL::isa() and should instead use $obj->isa() or CLASS->isa().

This means

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 08:42

    Assuming your example of what you want to be able to do is within an object method, you're being unnecessarily paranoid. The first passed item will always be either a reference to an object of the appropriate class (or a subclass) or it will be the name of the class (or a subclass). It will never be a reference of any other type, unless the method has been deliberately called as a function. You can, therefore, safely just use ref to distinguish between the two cases.

    if (ref $_[0]) {
      my $self = shift;
      # called on instance, so do instancey things
    } else {
      my $class = shift;
      # called as a class/static method, so do classy things
    }
    

提交回复
热议问题