mattsears18
mattsears18

Reputation: 144

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
            }

        }
    }
}

Upvotes: 0

Views: 36

Answers (2)

mattsears18
mattsears18

Reputation: 144

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.

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.

Upvotes: 0

John Conde
John Conde

Reputation: 219844

This is exactly what the __get() magic method is for. 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;
}

Upvotes: 2

Related Questions