function_exists返回false,但声明抛出错误 [英] function_exists returns false but declaration throws error
问题描述
public function chunkText()
{
if(!function_exists('unloadChunkText')){
function unloadChunkText(){
。 。 。
}
}
。 。 。
}
其中unloadChunkText是chunkText的辅助方法。问题是,无论何时我调用$ obj-> chunkText(),都会收到此错误:
无法重新声明diagnostic \question\ unloadChunkText()(以前在
file.php中声明的
: 34 )
在file.php中
在线 34
为什么function_exists不告诉我这个函数已经存在?
您正在检查全局函数 unloadChunkText
,而不是命名空间特定的函数 diagnostic \question \unloadChunkText
。但是我怀疑你的方法是有缺陷的。
如果你的方法 chunkText()
有助手函数,
作为关闭:
<$ p $公共函数chunkText()
{
$ unloadChunkText = function(){
//。 。 。
};
//。 。 。
//称之为$ unloadChunkText()
}
作为对象的私有方法:
private function unloadChunkText()
{
//。 。 。
}
public function chunkText()
{
//。 。 。
//称之为$ this-> unloadChunkText()
}
将其定义为私有方法可能更有意义,因此每次调用 chunkText()
时都不会浪费时间重新定义它。
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?
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()
.
这篇关于function_exists返回false,但声明抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!