繁体   English   中英

OOP PHP中的未定义变量

[英]Undefined variable in OOP PHP

我正在尝试向OOP PHP过渡,以帮助清理当前正在使用的代码集群。

我正在使用PHPass对数据库中的密码进行哈希处理,但是使用这种OOP方法,我无法在类的登录函数中全神贯注于如何调用它。

据我所知,在所有尝试调用它的地方,它总是在类初始化之前声明的,但它仍在告诉我它是未定义的或非对象。

db_config.php

...
require_once("PasswordHash.php"); // Location no.1 to try it
$password_hash = new PasswordHash(8, FALSE);

include_once("DB.php");
$db = new DB($db_connection);

...

init.php

//require_once("PasswordHash.php"); // Location no.2 to try it
//$password_hash = new PasswordHash(8, FALSE);

require_once("db_config.php")

..Other init stuff..

数据库

class DB {
   ... 
   public function login() {
      // global $password_hash; -> if uncommented I get an error saying it's a non-object

      // Error here 
      $password_accepted = $password_hash->CheckPassword($p, $hp);
   } 
   ...
}

login.php

require_once("init.php");

$db->login();

我仍然对类作用域在PHP中的工作方式一无所知,所以我感觉自己缺少一些东西。

您需要将哈希传递到类中,因为该类只有一个内部作用域。

$formData = array();
$formData['email'] = 'user@email.com';

require_once("PasswordHash.php"); // Location no.1 to try it
$formData['password_hash'] = new PasswordHash(8, FALSE);

include_once("DB.php");
$db = new DB($db_connection, $formData);

并在DB.php中:

class DB {
  // Stores the user input form data for use within the class?
  private $formData;
  // Runs when the class is constructed
  public function __construct($formData)
  {
    // When the class is constructed then store this for local/interal use
    $this->$formData = $formData;
  }
  public function login() {
    // The boolean result of of checking of an internal method
    // that compares user credentials against the database information?
    $password_accepted = $this->CheckPassword(
      $this->formData['email'], 
      $this->formData['password_hash']
    );
  }
  private function CheckPassword($email, $pass) {
    // Do query and bind in $user and $pass
    // Return true if everthing passes
  }
}

编辑:我夸大了将变量传递到类和方法中的用途,以帮助您绕开这方面的事情,但是您也可以执行以下操作:

    ...
    $password_accepted = $this->CheckPassword();
  }
  private function CheckPassword() {
    // Do query and bind in $this->formData['email'] and $this->formData['password_hash']
    // Return true if everthing passes
  }
}

只需像使用db_connection一样入哈希实例即可。

class DB {
    ...
    public function __construct($db_connection, $password_hash) {
        // you probably already have something like
        $this->connection = $db_connection;
        // now do the same for the hash object
        $this->pwhash = $password_hash;
    }

    public function login() {
    ...  
        $password_accepted = $this->pwhash->CheckPassword($p, $hp);
        ...
    }
}

(稍微偏离主题:数据库和哈希...以及密码,电子邮件和缓冲区,这些是我最不喜欢的类,供初学者捣蛋)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM