PHP函数没有';行不通

PHP函数没有';行不通,php,html,Php,Html,我试图使用User类中的私有变量存储在文本字段中输入的值。函数名在page index.php中运行良好,但一旦我重定向到profile.php,用户类就无法检索数据。这可能是因为我在profile.php中定义了一个新对象。我这样做只是为了测试。任何关于如何解决这个问题的建议 <?php session_start(); require_once 'Classes/User.php'; $user = new User(); if(isset($_POST['username'],$_

我试图使用User类中的私有变量存储在文本字段中输入的值。函数名在page index.php中运行良好,但一旦我重定向到profile.php,用户类就无法检索数据。这可能是因为我在profile.php中定义了一个新对象。我这样做只是为了测试。任何关于如何解决这个问题的建议

<?php 
session_start();
require_once 'Classes/User.php';
$user = new User();
if(isset($_POST['username'],$_POST['product'])){
$username = $_POST['username'];
$product = $_POST['product'];
if(!empty($product) && !empty($username)){
    $user->get('username');
    echo 'Success';
}
}

?>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>CSRF Protection</title>
</head>
<body>
    <form action="" method="POST">
        <div class="product">
            <strong>Profile</strong>
            <div class='field'>
                Username: <input type='text' name='username'>
            </div>
            <input type='submit' value='Order'>
            <input type='hidden' name='product' value='1'>
        </div>
    </form>
    <?php
    if(isset($_POST['username'])){
    ?>
    <p>Hello <a href = 'profile.php'><?php echo $user->name();?></a>!</p>
    <?php
    }
    ?>
</body>
</html>

<?php
class User{
private $_data;

public function get($item){
    if(isset($_POST[$item])){
        $this->_data = $_POST[$item];
    }
}

public function name(){
return $this->_data;
}
}

<?php
require_once 'Classes/User.php';
$user = new User();
echo 'Hello ' . $user->name();
?>

CSRF保护
个人资料
用户名:
你好!


您只能使用会话变量这样传递。在索引中添加以下代码

session_start();
$_SESSION['username'] = $user->name();   
在您的profile.php中

<?php 
session_start();
echo $_SESSION['username'];
<?php
require_once 'Classes/User.php';
$user = new User();
echo 'Hello ' . $user->name();
?>

我假设您在将表单发布到profile.php时得到一个空值

<?php 
session_start();
echo $_SESSION['username'];
<?php
require_once 'Classes/User.php';
$user = new User();
echo 'Hello ' . $user->name();
?>
在Classes/User.php中

<?php
class User{
    private $_data;

    public function get($item){
        if(isset($_POST[$item])){
            $this->_data = $_POST[$item];
        }
    }

    public function name(){
    return $this->_data;
    }
}


您从未调用$user->set('username'),因此$user->\u数据为空。

php变量不是超级全局变量很高兴我能提供帮助。如果您想获得更深入的理解,可以阅读PHP手册中的更多内容。