2017-08-13 139 views
-1

这是可能的在PHP?我有点新鲜和学习。功能里面的函数里面的函数,调用未定义的函数

//file name: functions.php: 
<?php 
function addItem(){ 
...does something 
// calls for another function in the same functions.php file 
randomNumber(); 
} 

function randomNumber(){ 
//generates random number 
} 

////////////////////////////////////// 
file name: worker.php 
<?php 
//calls for addItem() function 
addItem(); 
... 

function addItem(){ 
//calls for randomNumber() function 
.... 
$itemId = randomNumber(); 
..... 
} 

,所以我不断收到错误:调用未定义功能randomNumber() 因为我不包括在该的addItem functions.php文件()函数, 但是,如果我有它,我一直在歌厅无法重新声明firstFunctionOnFunctionsFile()我已经声明它。

有什么想法?

在此先感谢。

+0

更改检查文件是否已经被包含,如果是这样,不包括(要求),它的名字 – user2182349

回答

0

您正在调用未定义的函数。

//file name: functions.php: 
<?php 

function randomNumber(){ 
//generates random number 
} 


function addItem(){ 
// calls for another function in the same functions.php file but set before 
randomNumber(); 
} 

不同的需要,包括被包括不返回任何错误,将停止脚本,如果需要的文件不存在运行之间:既然你调用该函数在randomNumber功能应该是之前的addItem。此外,require_once将再次

//file name: worker.php 
<?php 
require_once 'functions.php'; 
//generating new items and set return in a value 
$newitem = addItem(); 
1

看看include_oncerequire_once的文档,它们允许您仅包含一次文件,而不管您调用这些函数的次数多少次,这样可以防止出现错误。

另外想想你是什么时候和在哪里做你的包括。将文件包含在函数体中真的有意义吗?如果你有一个functions.php文件,它包含了你的worker.php文件中需要的许多函数,只需将它包含在worker.php的头部,这样你就不用担心后面的代码了。这也使得更容易一目了然地查看包含哪些不同的文件。

+0

感谢我没有尝试使用include_once包括功能的答复。 PHP但我keept geting相同无法重新声明函数。 functions.php包含在worker.php文件中如果我不在函数中包含函数文件,它不会看到函数。我不认为PHP可以看到函数外的包含函数 –