Mr. D
Mr. D

Reputation: 55

How can i define a variable available to all php files(like superglobals)

Is there a way to create/define a variable available to all php files(like superglobals)

Example:

i define a variable in file1.php $car = ferrari

then in file2.php i write echo $car;

then it will output ferrari

how can i define a variable in file1.php and access it in file2.php

EDIT:

The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it.

Upvotes: 4

Views: 8095

Answers (4)

Denton
Denton

Reputation: 96

  • create init.php in your project's root directory.

If you need constant variable (so, you can't edit it) - create constants.php in your project's root dir.

If you need editable variable - create globals.php in your project's root dir.

constants.php

<?php
define('CAR', 'ferrari');

globals.php

<?php

class Globals
{
  public static $car = 'ferrari';
}

include constants.php and globals.php to init.php.

<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'constants.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'globals.php');

include init.php to php sources.

<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'init.php');

If you need variable for long use, not only one pageload, then use session. (user logins, settings, ...)

<?php
$_SESSION['car'] = 'ferrari';

In your php sources, you can use constant and global variables:

Example:

<?php
echo CAR; //ferrari

echo Globals::$car; //ferrari

Globals::$car = 'renault'; //set your global variable

echo Globals::$car; //renault

Refs:

http://php.net/manual/en/language.oop5.static.php

http://php.net/manual/en/function.define.php

http://php.net/manual/en/function.dirname.php

http://php.net/manual/en/reserved.variables.session.php

Upvotes: 5

Ramalingam Perumal
Ramalingam Perumal

Reputation: 1427

You can use SESSION or include concept.

1) By using SESSION

file1.php

session_start();
$_SESSION['car'] = 'ferrari';

file2.php

session_start();
echo $_SESSION['car'];  //Result: ferrari

2) By using include

file2.php

include 'file1.php';
echo $car //Result: ferrari

Upvotes: 1

masterFly
masterFly

Reputation: 1112

Hi The best way to do this is,

You make a .php file called "defines.php" and make sure to include that file in your each .php files.

make your variables, constants sits in that file. So that you can access them.

Other method would be, you can set the values to a existing Global variable.

like,

$_SERVER['car'] = "ferrari"

Thanks.

Upvotes: 0

Divyesh Savaliya
Divyesh Savaliya

Reputation: 2740

Create one constant file and include it in file in where you want to access those constants.

Include file as

include 'file_path';

Upvotes: 1

Related Questions