简体   繁体   English

如何在PHP类中定义方法数组?

[英]How might I define an array of methods within a PHP class?

I need to define several methods within a class. 我需要在一个类中定义几个方法。 The methods are very similar, so I would like to create an array of the method names and then generate all of the methods from this array of names. 这些方法非常相似,因此我想创建一个方法名称数组,然后从该名称数组生成所有方法。 I don't need to call the methods, just define them so that they're callable elsewhere. 我不需要调用方法,只需定义它们即可在其他地方调用它们。

I don't necessarily like that I have to define these methods this way, but the method names are set in stone. 我不必一定要这样定义这些方法,但是方法名称是固定不变的。

Something like this maybe: 可能是这样的:

class ProjectController
{
    public function __construct()
    {
        $this->makeMethods();
    }

    public function makeMethods()
    {
        $methods = ['Documents', 'Addenda', 'Docreleases', 'Drawings'];

        foreach($methods as $m){
            $method_name = 'get' . $m;

            /*
             * Define a method named $method_name on ProjectController
             * (I know the statement below is wrong. How might I fix it? I'm almost certain that I'm using '$this' incorrectly here, but I'm not sure what to use. '$this' should be a reference to ProjectController.)
             */

            $this->$method_name = function(){
                // do something
            }

        }
    }
}

This is exactly what the __get() magic method is for. 这正是__get()魔术方法的用途。 No need to have getters for all of the variable class members that exist. 不需要为所有存在的所有变量类成员获取吸气剂。 Just fetch them dynamically. 只需动态获取它们。

public function __get($var) 
{
    return $this->$var;
}

As I said, the method names are set in stone. 如我所说,方法名称是固定的。 I'm not trying to just define getters for properties, I'm trying to define routes for implicit controllers using Laravel http://laravel.com/docs/5.1/controllers#implicit-controllers . 我不只是尝试为属性定义getter,而是尝试使用Laravel http://laravel.com/docs/5.1/controllers#implicit-controllers定义隐式控制器的路由。

I ended up doing this: 我最终这样做:

public function __call($method, $args) {
    $action = substr($method, 0, 3);
    $resources = ['Documents', 'Addenda', 'Docreleases', 'Drawings'];
    $resource = substr($method, 3);

    if($action == 'get' && in_array($resource, $resources)){
        // do something
    }
}

Thanks for the magic method reference. 感谢您提供魔术方法参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM