如何动态调用对象的方法?
在 Perl 中,我知道您可以使用 eval
和 *{$func_name}
动态调用函数,但是如何使用对象的方法来执行此操作?
例如
EZBakeOven
sub make_Cake { ... }
sub make_Donut { ... }
sub make_CupCake { ... }
sub make_Soup { ... }
sub make{
my($self,$item) = @_;
if( defined $self->make_$item ){ #call this func if it exists
$self->make_$item( temp => 300, with_eggs => true );
}
}
,如果我说类似的话,
$self->make('Cake');
#or maybe I have to use the full method name
$self->make('make_Cake');
它会打电话给
$self->make_Cake();
in Perl I know you can use eval
and *{$func_name}
to call functions dynamically but how do you do this with methods of an object?
for example
EZBakeOven
sub make_Cake { ... }
sub make_Donut { ... }
sub make_CupCake { ... }
sub make_Soup { ... }
sub make{
my($self,$item) = @_;
if( defined $self->make_$item ){ #call this func if it exists
$self->make_$item( temp => 300, with_eggs => true );
}
}
so that if I say something like
$self->make('Cake');
#or maybe I have to use the full method name
$self->make('make_Cake');
it will call
$self->make_Cake();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够执行以下操作:
编辑:您可能还想使用
can()
来确保您正在调用的方法可以被调用:>编辑2:事实上,现在我想起来,我不确定你是否真的能做到这一点。我之前编写的代码执行类似的操作,但它不使用对象,而是使用类(因此您正在调用类中的特定函数)。它可能也适用于对象,但我不能保证。
You should be able to do something like:
Edit: You might want to also use
can()
to make sure you're calling a method that can be called:Edit 2: Actually, now that I think about it, I'm not sure if you really can do that. Code I've written before does something like that, but it doesn't use an object, it uses a class (so you're calling a specific function in a class). It might work as well for objects, but I can't guarantee it.
正如 @CanSpice 建议使用
can
来检查类和对象中是否存在方法。can
返回对该方法的引用(如果存在),否则返回 undef。您可以使用返回的引用直接调用该方法。
以下示例在包/类上下文中调用该方法。
__PACKAGE__
返回当前包/类名称。As by @CanSpice suggested use
can
to check a methods existence in classes and objects.can
returns a reference to the method if it exists, undef otherwise.You can use the returned reference to call the method directly.
The following example calls the method in package/class context.
__PACKAGE__
returns the current package/class name.