I couldn't find anything regarding my issue while searching. Maybe I wasn't wording my search properly. Anyway, I the am trying to call a function from another file from inside another function, but it isn't working. It appears to be a scope issue. I have the following:
File1.php:
<?
function myCoolFunction()
{
// Some really cool stuff in here
}
Then in File2.php:
<?
require('File1.php');
// A bunch of stuff
function anotherCoolFunction()
{
// Do some stuff
myCoolFunction();
}
myCoolFunction does not exist inside of anotherCoolFunction. I can call it in File2.php but not within another function. So my question is, how can this be achieved? Is there such thing as a super global function in php?
Thanks for any help!
For starters, use the function
keyword to define functions.
When you require a file in the way that you are you are bringing its contents into the scope of the file you are in. (Files within a namespace are a different story.)
Think of your File2.php
:
<?
require('File1.php');
// A bunch of stuff
function anotherCoolFunction()
{
// Do some stuff
myCoolFunction();
}
The same thing as doing:
<?
function myCoolFunction()
{
// Some really cool stuff in here
}
// A bunch of stuff
function anotherCoolFunction()
{
// Do some stuff
myCoolFunction();
}
Lastly, (and I only say this because I don't see it in your code) make sure you call the encapsulating function. E.g.
$var = anotherCoolFunction();
It would have worked if you'd correctly defined your functions
function myCoolFunction()
{
echo 'hello'; // Some really cool stuff in here
}
function anotherCoolFunction()
{
// Do some stuff
myCoolFunction();
}
anotherCoolFunction();
next time try enabling error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
It shall work now, points : using short tags is not recommended. If you can't find error don't just stackOverflow it put this beautiful ini_set() display error utility set by php.ini and yea.. you dint use function keyword before declaring function.
<?php
function myCoolFunction()
{
// Some really cool stuff in here
}
<?php
ini_set("display_error",1);
require('File1.php');
// A bunch of stuff
function anotherCoolFunction()
{
// Do some stuff
myCoolFunction();
}