Jump to content

function not working in include file...


whitsey

Recommended Posts

I am trying to put a function into an include file and use it elsewhere in my app.  I do not code that much but I thought I had done this before with success... But this appears to be a big problem I can't overcome...

 

I have a file:

 

/include/myfile.php which contains:

function myFunc() {
  return 2+2;
}
print "file included";

 

then in index.php:

 

include("/include/myfile.php");

echo myFunc();

 

Now this should work shouldn't it??? I can't for the life of me make it work...

 

The weird part is that I call 

echo myFunc();

I get the string "file included" printed to screen but also an error:

Fatal error: Call to undefined function myFunc()

 

I just don't get it!!! The file is being included - why can't I call the function?

Link to comment
https://forums.phpfreaks.com/topic/199654-function-not-working-in-include-file/
Share on other sites

The leading slash in the file path you are putting into the include() statement pretty much says that is not your actual code.

 

If you are using a URL in the include() statement, what you are doing won't ever work because that causes a separate http request to be made for myfile.php and the php code in it is parsed in a separate instance of the web server/php and the code does not exist in the same scope as index.php.

 

Use file system paths in include() statements.

The leading slash in the file path you are putting into the include() statement pretty much says that is not your actual code.

 

Yes, I am using a leading slash as I am including it from multiple different directories... Is this not achievable?  The error actually references the full path Fatal error: Call to undefined function myFunc() in /www/home/public_html/webserver/include/myfile.php

 

Can I not reference it directly?

The leading slash on a file system path refers to the root of the current hard disk. It does not refer to the document root folder.

 

The information you have shown in the thread does not match the symptoms. Best guess at this point is that you have multiple copies of the file in different directory paths, some with and some without the function definition and/or you are using short open tags in the included file (i.e. the "file included" is showing up because it is in the source, not because php is outputting it.)

 

What does a 'view source' of the page look like in your browser?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.