我可以使用一个变量来调用一个方法吗? [英] Can I use a variable to call a method?

查看:116
本文介绍了我可以使用一个变量来调用一个方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当方法名称存储在变量中时,我可以调用方法吗?语法是什么?假设我有以下PHP代码:

Can I call a method when the method name is stored in a variable? What's the syntax? Suppose I have the following PHP code:

class MyClass {
    public $default;

    function index() {
        /* call method named by $this->default */
    }
    function method_1() {}
    function method_2() {}
    ...
}

index()在类初始化时默认调用,如果没有特别调用其他方法。

index() is called by default when the class is initialised if no other method is specifically called.

使用 MyClass-> $ default 属性从 index()也就是说,如果我通常写:

How can I call one of the methods from within index() using the MyClass->$default property? That is, if I would ordinarily write:

function index() { $this->method_1(); }

我可以使用我的默认变量来调用正确的方法吗?

can I use my default variable to call the correct method?

推荐答案


我可以使用变量来调用方法吗?

Can i use a variable to call a method?

是的,你可以。例如,在一个对象内:

Yes you can. For example, inside an object:

$method = "method_1";

if (method_exists($this, $method))
 $this->{$method}();

这篇关于我可以使用一个变量来调用一个方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆