php - Assigning a function to a property of a class

22

I'm trying to do something similar to PHP anonymous function assigned to class property in constructor is always null?, but my solution seems more simple. I wanted comments from the Stack Overflow Hot Shots on this solution and whether there is a better one. This is kind of a 'best practices' question.

I want to pass a function (anonymous or defined) to a class/object and be able to call that function later. I started with this :

function Foo($arg) {return sprintf('In Foo(%s)',$arg);}
function Bar($arg) {return sprintf('In Bar(%s)',$arg);}

class TestIt {
  private $func;

  public function __construct( $func ) { $this->func = $func; }

  public function OutPut($arg) {
    return $this->func($arg);
  }
}

$test  = new TestIt('Foo');
echo $test->OutPut('Bozo');

When this is run, I get an error that the method$this->func doesn't exist. If I put ais_callable test inside the methodOutPut(), I find the$this->func is, in fact, callable, but the error persists.

However, if I us the third argument ofis_callable, I get this to work fine.

public function OutPut($arg) {
  return is_callable($this->func,false,$tmpfunc) ? $tmpfunc($arg) : null;
}

How does this stack up as a solution? Curious of your thoughts.

378

Answer

Solution:

Because there is no way to get PHP to parse$this->func() as a variable function, you have two options here:

return call_user_func_array($this->func, array($arg));

Or:

$func = $this->func;
return $func($arg);

is_callable() will return a static method callsomeClass::someMethod even if it is not a static method and is called in object scope.

People are also looking for solutions to the problem: PHP Soap - Save an xml server-side using nusoap

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.