【问题标题】:Why can't this function see the variables of a file included in an included file?为什么这个函数看不到包含文件中包含的文件的变量?
【发布时间】:2013-02-08 20:59:23
【问题描述】:

第一次发帖! 好的,我有一个包含此代码的函数:

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

还有

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

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

但是,如果我再次包含strap.php,我会收到错误:Cannot redeclare __autoload() (previously declared in D:\wamp\www\testing\scripts\CMS\strap.php:16) in D:\wamp \www\testing\scripts\CMS\strap.php 第 23 行

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

【问题讨论】:

    标签: php variables scope undefined require


    【解决方案1】:

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

    global $conf, $pdo;
    

    【讨论】:

    • 谢谢,很有魅力,但我不太明白。如何在无法正常访问它们的函数中将这些变量声明为全局变量?
    • 其实没用,肯定报错没了,但显然变量是空的,不应该的。
    【解决方案2】:

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

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

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

    需要'config.php';

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

    在内部,您的 setter 和类可能如下所示:

    ...

    /** 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,它的陷阱。

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2017-01-11
      • 1970-01-01
      • 2010-11-07
      • 2011-11-07
      • 2011-07-17
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多