简体   繁体   中英

Why is this Variable Disappearing?

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 = '../'; ?> <?php $pathprefix = '../'; ?>

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM