dave
dave

Reputation: 15479

how to set variables in a php include file?

I have a set of variables that are set outside the target php include file, how would i set them in the target php include file. Example:

<?php
  $fname = "david";
?>

Now how would I set $fname in another php file?

Upvotes: 2

Views: 12650

Answers (3)

James An
James An

Reputation: 1383

The PHP docs have an article about variable scopes.

The global variable scope is shared across all included and required files. In your example, once you've defined $fname globally, all other PHP lines executed afterwards can access $fname even if they're in different files.

Example: if a.php is:

<?php
  $fname = "david";
?>

and b.php is:

<?php
  $fname = "sarah";
  include 'a.php';
  // $fname is now "david"
?>

then executing b.php would define $fname as "sarah", then redefine it as "david" (through a.php).

Upvotes: 0

benck
benck

Reputation: 2052

Just use it directly.

$fname = "your value";

Upvotes: 0

Treffynnon
Treffynnon

Reputation: 21563

In your other PHP file you would do:

<?php
  $fname = "david";
?>

This answers your question directly, but I would hazard a guess that you actually want to have access to variables that are set in a file that is included into your current file or something along those lines.

So

File1.php:

<?php
  $fname = "david";
?>

File2.php

<?php
require_once 'File1.php';
echo $fname;

Would result in david being printed to screen.

Upvotes: 9

Related Questions