tags:

views:

61

answers:

2

This should probably have a simple answer I just can't figure out.

Anyway, I have a php document and inside of it I define <?php $pathprefix = '../'; ?>

Later in the document I use an <?php require([somefile.php]); ?> and inside of somefile.php, I have a line that says <?php echo($pathprefix); ?> but the '../' I assigned to $pathprefix never shows up. It acts like the variable was never instantiated. What is my problem?

A: 

The variable is out of scope in "somefile.php". You could declare the variable global, ie global $pathprefix = '../'. Then in somefile.php put global $pathprefix; at the top.

jdswift
that is incorrect - the variable is still very much in scope when require/include is used. It will be out of scope inside of a function, but not just because it's in another file
Marek Karbarz
I didn't say it was out of scope because it is in another file, I said it IS out of scope in somefile.php, probably because the $pathprefix is being first set in a function or is being called in a function. Either way, making it global might be a nasty solution, but it would work.
jdswift
+1  A: 

Really need to see your source code to determine the scope. With what you've provided here's two options:

Set in $GLOBALS

file1.php:

$GLOBALS['pathprefix']= '../';

file2.php:

require('file1.php');
print_r($GLOBALS['pathprefix']);

Use a class

file1.php:

class Settings {
 const PATH_PREFIX= '../';
}

file2.php:

require('file1.php');
print_r(Settings::PATH_PREFIX);

Understand Scope in PHP

http://www.php.net/manual/en/language.variables.scope.php

Good luck.

pygorex1