我在访问类时遇到问题。
索引.php
include('includes/header.php');
include('includes/step1.php');
include('includes/footer.php');
头文件.php
session_start();
include('php/classes/Errorhandler.php');
include('php/classes/User.php');
$errorhandler = new Errorhandler();
$user = new User();
// Test
print_r($errorhandler->errors);
...html
错误处理程序.php
class Errorhandler {
public $errors = array();
...
}
用户.php
class User {
public function __construct() {
if($this->grab_computerid()) {
if(!$this->grab_mandant()) {
$errorhandler->errors[] = "102: There was an error.";
}
if(!$this->grab_os()) {
$errorhandler->errors[] = "103: There was an error.";
}
} else {
$errorhandler->errors[] = "101: There was an error.";
}
}
private function grab_computerid() {
$sqlconnection = new SqlConnection();
$conn = $sqlconnection->db_connect();
if ($conn) {
$query = "SELECT Computer_Idn FROM " . DB_PC_TABLE . " WHERE DeviceName = ?";
$params = array($this->get_hostname());
if ($sqlconnection->query($query, $params)) {
$computer_id = $sqlconnection->fetchRow();
$this->set_computer_id($computer_id['Computer_Idn']);
return true;
echo "Test";
} else {
$errorhandler->errors[] = "Statement error occurred.";
}
} else {
$errorhandler->errors[] = "Can't connect to database.";
// test
print_r($errorhandler->errors);
}
$sqlconnection->db_disconnect();
}
}
index.php 包含构建站点的相关部分。在 header.php 中,我创建了两个对象(1. errorhandler,2. user)。User 类检查来自 sqlconnection 的返回(布尔值)。我知道,我使用了错误的密码并得到了错误的密码。所以 if ($conn) 正确打印 print_r($errorhandler->errors) 。但是当我想在 step1.php 中显示错误时,数组错误是空的。
step1.php
// show negative messages
if ($errorhandler->errors) {
foreach ($errorhandler->errors as $error) {
echo '<div class="alert alert-danger message"><strong>Error: </strong>' . $error . '</div>';
}
}
我也在 header.php 中对其进行了测试,并且错误数组也是空的。所以,errors 数组只填写在 User.php 类中,但我想在 step1.php 中显示错误。包含有问题吗?
编辑:希望让它更清楚:
头文件.php
// load the class Errorhandler
require_once('php/classes/Errorhandler.php');
// load the class User
require_once('php/classes/User.php');
// create errorhandler object
$errorhandler = new Errorhandler();
// create user object
$user = new User();
print_r($errorhandler->errors);
我在用户类中设置了一个错误:
$errorhandler->errors[] = "Can't connect to database.";
header.php 中的数组 $errorhandler->errors 为空。