scope - PHP - Accessing variables in an included script from an included script -


i have list of files require_once @ beginning of main scripts.

in 1 of files, have bunch of functions.
in 1 of files, have bunch of constants (which variables @ moment, constants).

main.php

require_once \constants.php require_once \functions.php 

from within main.php, able call functions , call constants respective scripts... able call functions , pass constants constants.php parameters functions.
however, not able use functions have constants embedded within them.
in other words, cannot use functions functions.php have variables constants.php file within functions, able use functions functions.php if not have variables other included files within function.

function firstfunction(){ echo $constant1; return 1 } 

firstfunction() uses $constant1 constants.php , not work.

function secondfunction($param){ echo $param; return 1 } 

secondfunction() can passed $constant1 constants.php parameter , works fine.

questions:

is there way me able use main.php call function file , constant file , have function file use variables constant file without explicitly calling or passing them within main.php?

if daisy chain them (main.php calls functions.php; functions.php calls constants.php) work? (i kind of tried not enough either trust or rule out method yet).

note

most of information able find regarding using variables included files, not included files using variables other included files.

this sounds simple scope issue, has nothing include-cycle.

when create 'constants' normal php-variables ($name='value';), in root scope of constants.php, must called inside later functions, referencing them first ... this:

$name='value';      /** other stuff **/  function foo(){     global $name;     //you have access $name here } 

the true solution tho, define constants real constants, makes them available in scope ... this:

define('name','value');      /** other stuff **/  function foo(){     //you have access name here } 

only downside true constants is, constant ... meaning, can’t changed @ later point in script.

you can read more 'scope' here: http://php.net/manual/en/language.variables.scope.php


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -