DaOgre
DaOgre

Reputation: 2100

Trouble setting up closures for class methods

I am architecting out a class and so far have something roughly like the following

in main.php

$coolObject = new CoolObject(true);

foreach($array as $key=>$val)
{
    $coolObject->doFunction($val);
}

then inside of CoolObject:

class CoolObject
{
    private $_useFunction;

    public function __construct($useFoo)
    {
        //THIS IS WHERE I NEED HELP
        if($useFoo){
            $this->_useFunction = $this->_foo();
        }
        else{
            $this->_useFunction = $this->_bar();
        }
    }

    public function doFunction($values)
    {
        $this->_useFunction($values);
    }

    private function foo($values){
        //do stuff
    }

    private function bar($values){
        //do other stuff
    }
}

I realize I could put an if statement or switch into doFunction that could handle this functionality, but since I'm not hip on closures/lamdas I wasn't sure if this is the right situation for them or if I'm just totally off base

Upvotes: 0

Views: 25

Answers (1)

Juan Nunez
Juan Nunez

Reputation: 529

What you're trying to achieve (as far as I know) are function pointers in PHP.

You should really take a look in: Array Pointer to a function in PHP

I still think inheritance will be the easiest/cleaniest way to solve this.

So you would probably end with:

class CoolObject { private $_useFunction;

public function __construct($useFoo)
{
    //THIS IS WHERE I NEED HELP
    if($useFoo){
        $this->_useFunction = 'foo';
    }
    else{
        $this->_useFunction = 'bar';
    }
}

public function doFunction($values)
{
//Edited as @newacct corrects
$this->$_useFunction($values); 
}

private function foo($values){
    //do stuff
}

private function bar($values){
    //do other stuff
}

}

Upvotes: 1

Related Questions