开发者

How can I correctly require a file and make use of it's variables?

I am writing a simple PHP script that make use of DB to export some products. My code starts like

$host = "localhost";
$user = "";
$pass = "";
$database = 开发者_Python百科"";

letting user to add those info. However is there any way to make use configuration.php file that it is saved in the same directory

What I did is this but I didn't got any result

require('configuration.php');
echo $user;

This is the configuration.php file

<?php
class JConfig {
var $dbtype = 'mysql';
var $host = 'localhost';
var $user = 'user';
var $password = 'pass';
var $db = 'db';
}
?>


If you use a class for the configuration (why ?) then you have to initialize it. or use static class vars.

require('configuration.php');

$config = new JConfig;
echo $config->user;

you could also use just defines e.g

define('DB_USER', 'yourusername');
define('DB_PASS', 'yourpassword');

after include/requiring it, you just do:

echo DB_USER;

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


EDIT: after your edit i think you mean something diffrent.

you will need 2 config files. config_default.php config.php

users write their config in config.php you have yours in config_default.php

you will have to include config_default.php first and than config.php. be notet this only works with variables. if you use classes you will have to write code to init the classes with the correct configuration variables.


 class JConfig {
    public static $dbtype = 'mysql';
    public static $host = 'localhost';
    public static $user = 'user';
    public static $password = 'pass';
    public static $db = 'db';
    }

and Access direct in you file were u have included that file

JConfig::$user // return 'user'

Reference


require('configuration.php'); 
$config = new JConfig;
echo $config->user;


You won't get a result from including/requring your configuriation.php file as it stands, but you've had the right idea.

If you remove the JConfig class wrapper around those variables, you can use them as if they were local variables, once you include/require the file.

configuration.php

<?php
var $dbtype = 'mysql';
var $host = 'localhost';
var $user = 'user';
var $password = 'pass';
var $db = 'db';
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜