Ian Hunter
Ian Hunter

Reputation: 9784

function_exists returns false but declaration throws error

In PHP 5.3.6 I have a class with a method like this:

public function chunkText()
{
  if(!function_exists('unloadChunkText')) {
     function unloadChunkText() {
        . . .
     }
  }
  . . .
}

Where unloadChunkText is a helper method for chunkText. The problem is that whenever I call $obj->chunkText() I am given this error:

Cannot redeclare diagnostic\question\unloadChunkText() (previously declared in file.php:34) in file.php on line 34

Why isn't function_exists telling me that this function already exists?

Upvotes: 2

Views: 1036

Answers (3)

Mike B
Mike B

Reputation: 32165

Provide the scope within function_exists():

function_exists('diagnostic\question\unloadChunkText')

Upvotes: 2

Kavi Siegel
Kavi Siegel

Reputation: 2994

The thing with function_exists is you can't provide a scope for it. Try using is_callable instead, where the callback would be array($this, 'unloadChunkText')

Or, method_exists is another possibility. method_exists($this, 'unloadChunkText')

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88697

You are checking for the global function unloadChunkText, instead of the namespace-specific function diagnostic\question\unloadChunkText. But I suspect your approach here is flawed.

If you have a helper function for your method chunkText(), define it in one of two ways:

As a closure:

public function chunkText()
{
  $unloadChunkText = function () {
    // . . .
  };
  // . . .
  // Call it like $unloadChunkText()
}

As a private method of the object:

private function unloadChunkText ()
{
  // . . .
}

public function chunkText()
{
  // . . .
  // Call it like $this->unloadChunkText()
}

Defining it as a private method probably makes more sense, so you don't waste time redefining it every time you call chunkText().

Upvotes: 2

Related Questions