为什么这个函数看不到包含在文件中的文件的变量?

时间:2013-02-08 20:59:24

标签: php variables scope undefined require

首先发布在这里! 好的,所以我有一个包含这段代码的函数:

require_once('../strap.php');

$admin = new Member;
$admin->setName($_POST['username']);
$admin->setPassword($hash);
$admin->setEmail($_POST['email']);
$admin->updateDatabase();

所需文件如下所示:

//define constants
define('ROOTPATH', __DIR__ . '/');
define('CLASSES', __DIR__ . '/classes/');

//Lazy load any required php classes
function __autoload($class_name) {
    $file = CLASSES . $class_name . '.php';
    if( file_exists($file) ) {
        require_once $file;
    } else {
        echo "Can't find ". $file;;
    }
}

//does config exist?
if (!file_exists('config.php')) {
    //redirect to install routine if config does not exist
    header(ROOTPATH . 'admin/install.php') ;
}

require('config.php');

//connect to the database
try {
    $pdo = new PDO('mysql:database='.$conf['database'].';host='.$conf['host'].';port='.$conf['port'].';', 
    $conf['username'], $conf['password']);
} catch(PDOException $e) {
    die('ERROR: Could not connect: ' . print_r($e->getMessage()));
}

并且该(config.php)中的所需文件如下所示:

$conf['username'] = 'root';
$conf['password'] = '';
$conf['host'] = 'localhost';
$conf['database'] = 'dddatabase';
$conf['port'] = '3306';
$conf['prefix'] = 'cms_';

我的问题是我收到此错误:注意:未定义的变量:第152行的D:\ wamp \ www \ testing \ scripts \ CMS \ classes \ Member.php中的conf

以及

注意:未定义的变量:第153行的D:\ wamp \ www \ testing \ scripts \ CMS \ classes \ Member.php中的pdo

初始化一个新的Member对象,然后调用updateDatabase()方法,该方法使用$ conf []数组和$ pdo对象。

然而,如果我再次包含strap.php,我会收到错误:无法重新声明__autoload()(之前在D:\ wamp \ www \ testing \ scripts \ CMS \ strap.php:16中声明)在D:\ wamp中第23行\ www \ testing \ scripts \ CMS \ strap.php

有谁知道这里出了什么问题?

2 个答案:

答案 0 :(得分:1)

在您尝试访问$ pdo和$ conf变量的Member类中,您需要将它们声明为全局变量。因此,在Member类中,在您尝试使用这些变量的函数中,将以下内容添加到函数的开头(或者至少在引用它们之前):

global $conf, $pdo;

答案 1 :(得分:1)

我需要看看你的班级成员。

但是当您尝试使用未定义的对象变量时,会抛出此类错误。

您需要使用setter将$ conf传递给Member类,如下所示:

要求'config.php';

$member = new Member(); $member->setConfig($conf);

在内部,你的setter和class看起来像这样:

...

/** var array $config **/
private $config = array();


public function  setConfig(array $conf)
{
    $this->config = $conf;
}


public function getPort()
{
    return $this->config['port];
}

...

现在,我个人更喜欢只使用类并避免使用数组()。 如果其他人使用您的类结束,则必须理解数组结构而不是类定义。

快速重新实现您想要实现的目标,如下所示:

...

php INI File:

[database]
username =  root
password = 1234
database = localhost
host = localhost

// Immutable value Object



Class Config
{

    private $username;
    private $password;
    private $host;
    private $database;
    private $port;
    private $prefix;

    public function __construct($username, $password, $host, $database, $port, $prefix = 'db_')
    {
        $this->username = $username;
        $this->password = $password;
        $this->host     = $host;
        $this->database = $database;
        $this->port     = $port;
        $this->prefix   = $prefix;
    }

    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @return mixed
     */
    public function getDatabase()
    {
        return $this->database;
    }

    /**
     * @return mixed
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @return mixed
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * @return mixed
     */
    public function getPrefix()
    {
        return $this->prefix;
    }
}


// Entity



class Member
{
    private $name;
    private $password;
    private $email;
    private $config;


    public function setPost($post)
    {
        $this->name     = isset($post->name) ? $post->name : 'admin';
        $this->email    = isset($post->email) ? $post->email : 'admin@localhost';
        $this->password = isset($post->password) ? $post->password : '1234';
    }

    /**
     * @param mixed $config
     */
    public function setConfig($config)
    {
        $this->config = $config;
    }

    /**
     * @return mixed
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param mixed $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

}

class Connection
{
    /**
     * @var  Config $config
     */
    private $config;
    private $connection;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function connect()
    {
        if (!$this->connection instanceof \PDO) {
            $this->connection = new \PDO(
                'mysql:database=' . $this->config->getDatabase() .
                ';host=' . $this->config->getHost() .
                ';port=' . $this->config->getPort() . ';',
                $this->config->getUsername(),
                $this->config->getPassword()
            );
        } else {
            $this->connection;
        }
    }
}

...

然后我们应该:

define('ROOTPATH', DIR 。'/');     define('CLASSES', DIR 。'/ classes /');

//Lazy load any required php classes
function __autoload($class_name) {
    $file = CLASSES . $class_name . '.php';
    if( file_exists($file) ) {
        require_once $file;
    } else {
        echo "Can't find ". $file;;
    }
}

//does config exist?
if (!file_exists('config.ini')) {
    //redirect to install routine if config does not exist
    header(ROOTPATH . 'admin/install.php') ;
}

if(false == $config = parse_ini_file('config.ini')) {
    //Do something else
}


$post = (object)$_POST;
$configClass = new Config(
    $config['username'], 
    $config['password'],   
    $config['host'], 
    $config['database'], 
    $config['port']
);

$connection = new Connection($configClass);

try {
    $connection->connect();
} catch(\Exception $e) {
    die($e->getMessage());
}

$member = new Member();

//Either

$member->setPost($post);

//OR

$member->setName($post->name);
$member->setEmail($post->email);
$member->setPassword($post->password);


//I do not understand, what you are try to do below but its from your question

$member->updateDatabse();

...

我不确定你要在会员班上实现什么目标,这是活跃的记录吗?

不要使用GLOBALS,它的陷阱。