Moon
Moon

Reputation: 22565

How to call a class member as a closure?

I'm trying to make the following example works. It looks like PHP thinks $this->getData2 as a member variable. How do I make it so that PHP thinks it as a method?

class Test {

    public function getData()
    {
        return array(
            'data1'=>array('name'=>'david'),
            'data2'=>$this->getData2
        );
    }

    public function getData2()
    {
        return "hello"
    }

}

$test = new Test;
$data = $test->getData();

$data = $data['data2']();

I've tried the following, but looks like..I can't use $this in this case

function() use($this) {
   return $This->getData2();
}

Upvotes: 1

Views: 61

Answers (4)

StackSlave
StackSlave

Reputation: 10627

Try:

class Test {
  public function getData(){
    return array('data1' => array('name' => 'david'), 'data2' => 'getData2');
  }
  public function getData2(){
    return 'hello';
  }
}
$test = new Test; $data = $test->getData(); echo $test->$data['data2']();

Upvotes: 1

Barbara Laird
Barbara Laird

Reputation: 12717

class Test {

    public function getData(){
        return array(
            'data1'=>array('name'=>'david'),
            'data2'=>'getData2'
        );
    }

    public function getData2()    {
        return "hello";
    }

}

$test = new Test;
$data = $test->getData();

$data = $test->$data['data2']();

echo $data;

Wasn't working without the $test-> on the $data = $test->$data['data2'](); line

And because I love fiddles: http://phpfiddle.org/main/code/4f5-v37

Upvotes: 2

boen_robot
boen_robot

Reputation: 1538

A callable to a method is an array with the object as a first member, and the method name as a second one.

So:

class Test {

    public function getData()
    {
        return array(
            'data1'=>array('name'=>'david'),
            'data2'=>array($this, 'getData2')
        );
    }

    public function getData2()
    {
        return "hello";
    }

}

$test = new Test;
$data = $test->getData();

$data = $data['data2']();

Upvotes: 2

Ardenexal
Ardenexal

Reputation: 543

Easiest way would just be to do the calculation in a variable outside of the array and then just put the variable into the array

Upvotes: 0

Related Questions