Variable scope and includes - php

I have the following problem: in index.php, I have set the variable $activelang. I
$activelang = active_language ();
echo $activelang; //works perfectly
Later in my index.php code, I include a new php file.
include ('myotherfile.php');
If I try to use $activelang in myotherfile.php, it does not work! I am not using it inside a function, and I tried using global $activelang and it doesnt work either
All of these is happening in a wordpress install, but the code I am talking about is plain php. I am using php 5.3
Why is this happening? As I undestand it, the include works as a copy paste in my main file, so I shouldnt be having any problems with variable scope, right?

include should be used to include files, not some network resources.
if you bother to run the code you posted here you'll be surprized, as it will print $activelang all right.

When working with WordPress templates you should create functions in your functions.php file for handling includes and then call those functions in your templates.
So in functions.php you should have:
function myOtherFile() {
include('myotherfile.php');
}
And in index.php call myOtherFile()
Now, if you still have trouble with scope try this:
function myOtherFile($activelang) {
include('myotherfile.php);
}
And then in index.php do this:
$activelang = active_language();
myOtherFile($activelang);
If that doesn't work then I think your problem is being caused elsewhere. Because like Col. Shrapnel said, the code you posted here works.

Related

Proper way to require file that requires db connection

I don't use php very often and was wondering if someone could answer this question for me.
I have a folder structure like so:
-pages/rightCol.php
-pages/privacyPolicy.php
index.php
In my index file I have a connection to the database like this:
ob_start();
require($_SERVER['DOCUMENT_ROOT'] . "/inc/db.inc.php");
That works fine.
I wanted to separate out some repeated code between pages so I created the rightCol.php file. It needs the connection to the database. So right now I create a query result at the top of the index file and use the statement:
This works.
I also wanted to include it in the privacyPolicy.php page. This does not work because I do not want to put the query code at the top of every page that requires the rightCol.php file.
I would like to put the db stuff inside the rightCol.php. When I try this, then my privacyPolicy.php file works but then my index breaks. Probably because I require the db file twice, once at the top of the index and once in the rightCol.php file.
How can I set this up properly where I do not need to repeat code.
Thanks
EDIT
I changed my call to use require_once.
The privacyPolicy.php page works fine but when I view my index.php it has errors.
Error: No DB selected.
Include the db/inc.php only at the start of your index.php and open the connection. That way, it will stay open throughout the whole script. Then just close it at the very end of your site;
If you are having problem knowing where to include and not ( and still for some unknown reason want to include it more then once ), then get used to require_once method. This way the file will be included only once and the 2nd attempt will be ignored.
Well, the quick way to solve the problem is to use require_once. But i highly recommend that you use a micro-framework like Slim.

PHP variable scope between various template files

This is a newbie question, and I know it.
Template structure is your usual index.php, with a few require_once()'s for the header/footer etc.
I define a var at the top of index.php before any of the require_once()'s for the base url, such as $url = 'http://url';
I then want to echo this out into all template files, header/index/footer etc, it works inside index.php as expected, but fails with a undefined var in all template files that are included in.
I know it's a var scope issue, but I'm totally perplexed how to fix it.
I'm aware that the manual says vars are available to included files, however they aren't. Could it be a issue with my local PHP install?
edit : Created a couple of test files, and a var is defined between 2 files, so why are they not working on my main site files?
Any helps gracefully recieved.
Many Thanks
if you use functions or methods (functions in classes) then you need to do global $variable inside the function. Otherwise you will not have access to it, you also could define it as constant. A constant is always global.
define('MYURL', $url);
You might want to use a PHP framework, if you not already do so.

PHP $GLOBALS variable issue in included file

I recently moved a large CubeCart installation to a new server and it created a whole bunch of issues. Most of them I'm getting sorted out error by error, but I'm stuck on this one:
In the main index.php file the config file is included, which sets key variables like $glob['rootDir']. Then a few lines later in the main index.php file another important script is included and calls some of those $glob variables, but under the $GLOBALS superglobal. However this isn't working. If I put on the second included file var_dump($GLOBALS) it's all there... but if I put echo $GLOBALS['rootDir'] I get nothing.
I'm not getting any bad errors or anything, just Undefined Index.
Is this an issue with PHP settings? The site was working fine before on the previous server, though I don't know what version of PHP it was running or specific settings.
Code samples:
MAIN INDEX FILE:
//INCLUDE CORE VARIABLES & FUNCTIONS
include_once("includes/global.inc.php");
//... other stuff ...
include_once("includes/sessionStart.inc.php");
GLOBAL.INC.PHP:
$glob['dbhost'] = 'localhost';
//other variables, including $glob['rootRel'];
SESSIONSTART.INC.PHP:
$sessionDomain = substr($GLOBALS['rootRel'],0, strlen($GLOBALS['rootRel'])-1);
//the above is where it throws Undefined Index
Thanks!
$glob and $GLOBALS are different variables, so this behaviour is ok.

Include a php library and cant access it from another php page

Im loading the php rss parsing library simplepie onto my site and i include it in the header.php file like so:
<?php
// Make sure that SimplePie is loaded
require_once('inc/simplepie.inc');
$feed = new SimplePie('rss.com'); <-- This is a example url
// Make sure the content is being served out to the browser properly.
$feed->handle_content_type();
?>
Then i try to access the object from another page called page.php and it gives me this error:
Fatal error: Call to a member function get_items() on a non-object in /home/callofdu/public_html/wp-content/themes/Starkers/page.php on line 13
I get the error from this line of code:
<?php
foreach ($feed->get_items() as $item)
{}
?>
Its weird because if i include both of those chuncks of code together on the same php page it all works fine.
I just am not understanding something, please help.
Several things could be wrong here:
Code order is incorrect.
Realise that when you require or include a PHP file, the entire code of that file will be executed at that point. In other words: interpret the command require_once as "Insert file contents here", and check whether the order of lines of code are still right.
You are calling page.php in a separate request.
If you use your browser to manually surf to page.php after the completeion of the previous page, $feed will no longer exist. If you do want it to live on between requests, do the following:
a. Replace all instances of $feed with $_SESSION['feed']
b. In the first line of every file that you surf to (so not the require'd files), put session_start();
The require and include calls in php basically take the contents of that file and slap in place.
So if you follow the linear path that php taking while running a script, you have to make sure that the library is called before you use it.
Basically in practice, if you are executing page.php as a standalone then you will need to require it in that script also, however, if page.php is being included in the first script you mentioned then you don't need to require it again, but make sure the library is included before page.php
ie
<?php
// Make sure that SimplePie is loaded
require_once('inc/simplepie.inc');
$feed = new SimplePie('rss.com');
// Make sure the content is being served out to the browser properly.
$feed->handle_content_type();
require_once "page.php";
?>
doesn't need to be required in both
As for the differences between the require and include calls check out
http://www.php.net/manual/en/language.control-structures.php
EDIT:
After seeing this is Wordpress related, remember variable scoop. Variables do not inherent from a functions parent. So in page.php try:
<?php
global $feed;
foreach ($feed->get_items() as $item)
{}
?>
You need to include the libraries on EVERY page you're using the library's functions.
I think it is relative paths issue. Try using absolute paths. Or check if path to rss.com is okay. May be you need to call it in another way: $feed = new SimplePie('../rss.com');

PHP function getHeader()

Hey guys, Im building a fairly large website here, I am using quite a bit of php along with it, but what I was wondering, I have a header that does't change throughout the website, and I was wondering if I could create a function in some of my php code where all I would have to do is call like a function getHeader() and it will return the header. Now this header has some php in it also like a search bar and a username container... I was just wondering if this was possible on a fairly simple scale so I don't have to place the header code in each php file. which is fine but if I happen to make an update I have to update file which could take some time...
Thanks in advance!
Just create a header file (e.g. header.php) and include it.
http://php.net/manual/en/function.include.php
You can either have the code directly in the header.php not in any functions, and it will run by default, or put it in a function and call it manually.
A simple include() at the top of every file is what you'll need http://php.net/manual/en/function.include.php
You could use a function. That's what WordPress does. You could even put PHP inside them. You'd just have to keep in mind that the PHP inside your function is... well... inside a function. So you'd have to explicitly access global variables, etc.
Another option would be to put the header in its own, single file and just include that file, instead of calling a function. Whatever floats your boat.

Categories