函数内部函数函数,调用未定义函数

时间:2017-08-13 03:02:14

标签: php function

这可能在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()cus我已经声明了它。

任何想法?

提前谢谢。

2 个答案:

答案 0 :(得分:1)

查看include_oncerequire_once的文档,无论您调用这些函数多少次,它们都允许您只包含一次文件,这可以防止您看到的错误。

还要考虑你在做什么的时间和地点。在函数体中包含文件真的有意义吗?如果你有一个functions.php文件,其中包含你在worker.php文件中需要的一些函数,那么只需将它包含在worker.php的头部,这样你以后就不用担心它了。码。这也使我们更容易一目了然地看到包含哪些不同的文件。

答案 1 :(得分:0)

您正在调用未定义的函数。 randomNumber函数应该在addItem之前,因为你调用了函数:

//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();
}

require和include之间的区别是include如果不存在所需文件,则不返回任何会阻止脚本运行的错误。此外,require_once将检查文件是否已被包含,如果已包含,则不再包括(要求)

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