function_exists returns false but declaration throws error

寵の児 提交于 2019-12-12 18:29:23

问题


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?


回答1:


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().




回答2:


Provide the scope within function_exists():

function_exists('diagnostic\question\unloadChunkText')



回答3:


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')



来源:https://stackoverflow.com/questions/9316181/function-exists-returns-false-but-declaration-throws-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!