序列化/反序列化/OOP [英] Serialize / Deserialize / OOP

查看:122
本文介绍了序列化/反序列化/OOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我当时正在用一些oop练习arround并试图制作一个基本的oop User类,所以我尝试着制作系统,以便在每个页面上我都可以包含config.php并加载我需要的所有东西,但是由于某种原因一旦我尝试登录,它就会引发此错误:

So I was practicing arround with some oop and tried to make a basic oop User class I tried making my system so that on every page I can just include config.php and everthing I need gets loaded in, but for some reason as soon as I try to login it throws me this error :

致命错误:在非对象上调用成员函数LogIn()

Fatal error: Call to a member function LogIn() on a non-object

config.php:

config.php :

<?php
session_start();

// Mysql details
$username = "torlolol";
$password = "torlolol";
$hostname = "localhost";
$database = "torlolol";

// Autoloads classes when needed
function __autoload($class_name) {
    include 'Classes/' . $class_name . '.php';
}

$db = new DBConnector($hostname, $username, $password);

// If there is no user in the session stored make a new one otherwise unserialize it
if(empty($_SESSION['user']))
    $user = new User();
else
    $user = unserialize($_SESSION['user']);

function onExit()
{
    //When exiting the page serialize the user object and store it  in the session
    $_SESSION['user'] = serialize($user);
}

register_shutdown_function("onExit")
?>

login.php

login.php

<?php
include "config.php";
global $user;
$user->LogIn();
?>

用户类别:

class User {
    public $Logged = false;

    public function LogIn()
    {
        $this->Logged = true;
    }

    public function LogOut()
    {
        $this->Logged = false;
    }
}
?>

index.php:

index.php :

                <?php
                include "config.php"; 
                global $user;
                if ($user->Logged != true)
                    echo '<form action="login.php" method="post">Username :<input type="text" name="username" /> Password :<input type="password" name="password" />&nbsp;&nbsp;<input type="submit" value="Login" /></form>';
                else    
                    echo '<form action="logout.php" method="post"><input style="submit" value="Logout" /></form>';

那为什么会抛出该错误呢?以及为什么它不在索引文件中发生:S ?>

So why does it throw out that error ? And why isn't it happening in the index file :S ?>

推荐答案

在启动会话之前,您必须包括类文件,否则序列化的对象将无法正确加载.不幸的是...

You have to include the class-files BEFORE you start the session, otherwise serialized objects will not be loaded correctly. Unfortunately...

这篇关于序列化/反序列化/OOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆