开发者

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 th开发者_如何学Ce target php include file. Example:

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

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


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.


Just use it directly.

$fname = "your value";


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜